总结:是否可以在 onOpen() 上请求授权?
详细版本:我有一个带有按钮的电子表格,可以分发给很多人。当按下任何按钮时,会调用一些需要权限的函数,因此 Google Apps 脚本会显示此弹出窗口:
这被接受后,一切运行良好,因为它现在有授权。但是,当打开工作簿时,我想在按下按钮之前运行需要权限的东西。但是,如果您将需要授权的代码放入 onEdit 或 onOpen 函数中,默认情况下它会在没有特权的情况下运行并中途崩溃,而不是显示弹出窗口并请求权限。
以下是一些示例代码 - 崩溃而不是请求创建触发器的权限(也适用于 CalendarApp 等):
function onOpen(e) {
Browser.msgBox("This is shown to the user");
try {
ScriptApp.newTrigger('someFunction').forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet()).onEdit().create();
}
catch (e) {
Browser.msgBox(e);
}
Browser.msgBox("This message is never shown to the user if there is no try catch because it crashes");
}
Run Code Online (Sandbox Code Playgroud)