为什么当我创建菜单时,它显示 "Cannot call SpreadsheetApp.newMenu() from this context. "

why when I create a menu, it says "Cannot call SpreadsheetApp.newMenu() from this context. "

我部署了一个网络应用程序,它可以在电子表格打开时调用该函数来创建一个新菜单。 下面是我写的部分

function onOpen(){
  var url = "https://script.google.com/a/slt.org.au/macros/s/AKfycby2pFGHc3qWaxnD4WGTLMEAPMUocohzH_-OsUPxwqi8kmWfRZs8/exec";
  var currentSpreadsheet = SpreadsheetApp.getActive().getId();
  var requestAction = "onOpen";
  UrlFetchApp.fetch(url+"?requestAction="+requestAction);
}

在我的网络应用程序中,我写

function onOpen(currentSpreadsheet) {
  //Adds custom menu
SpreadsheetApp.openById(currentSpreadsheet);
  var menu = [{name: "Add row", functionName: "addRow"},
             {name: "Generate Invoice", functionName: "generateInvoice"}];
  SpreadsheetApp.getActiveSpreadsheet().addMenu("Custom", menu);
}

我有一个测试,我确定电子表格 ID 已经转移到函数中,但是它给我一个错误 "Cannot call SpreadsheetApp.newMenu() from this context. "

我也试过了

function onOpen(currentSpreadsheet) {
      //Adds custom menu
      var menu = [{name: "Add row", functionName: "addRow"},
                 {name: "Generate Invoice", functionName: "generateInvoice"}];
      SpreadsheetApp.openById(currentSpreadsheet).addMenu("Custom", menu);
    }

仍然无法正常工作。那么这是否意味着 addMenu 只能在独立或内置脚本中使用?但不在 google 网络应用程序中?

当我尝试使用 addMenu() 时出现所有错误。

您的脚本在 Web 应用程序的上下文中是 运行,但 onOpen() 触发器仅在绑定到 Docs/Sheet/Form 文件的脚本中运行。简而言之,您不能通过网络应用将 onOpen() 函数传递或安装到电子表格中。

来自documentation

To use a simple trigger, simply create a function that uses one of these reserved function names:

onOpen(e) runs when a user opens a spreadsheet, document, or form that he or she has permission to edit. ...