强制要求授权 onOpen()(强制弹出)

Aug*_*e C 5 permissions authorization google-sheets google-apps-script

总结:是否可以在 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)

Ala*_*lls 4

注意:简单触发器无法访问需要授权的服务。例如,简单的触发器无法发送电子邮件,因为 Gmail 服务需要授权

onOpen()是简单触发器函数的保留函数名称。

有一种方法可以检查授权状态,如果代码需要授权,则可以获取授权URL。但是,如果该ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL)方法需要用户授权,那么它在运行时将不起作用onOpen()

onOpen方法无法打开侧边栏,因此无法从onOpen触发器检查授权状态。用户需要先单击打开侧边栏或对话框的菜单项。

我不确定代码“ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL)”是否能正常工作。要强制重新授权提示,您可能需要运行导致评估范围的代码。

代码.gs

function onOpen() {
  //Create custom menu or add-on menu
}

function showSidebar() {
  var html = HtmlService.createTemplateFromFile('HTML_Sidebar').evaluate()
      .setTitle('Log Tools')
      .setWidth(300);
  SpreadsheetApp.getUi() 
      .showSidebar(html);
}
Run Code Online (Sandbox Code Playgroud)

HTML_侧边栏

<!DOCTYPE html>
<html>
  <head>
    <base target="_blank">
  </head>
  <body>

    <div><?!= getAuthUrl(); ?></div>
  </body>

</html>
Run Code Online (Sandbox Code Playgroud)

GS_侧边栏

function getAuthUrl() {
  var authInfo,msg;

  authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);

  msg = 'This spreadsheet needs permission to use Apps Script Services.  Click ' +
    'this url to authorize: <br><br>' + 
      '<a href="' + authInfo.getAuthorizationUrl() +
      '">Link to Authorization Dialog</a>' +      
      '<br><br> This spreadsheet needs to either ' +
      'be authorized or re-authorized.';

  //return msg;//Use this for testing

  //ScriptApp.AuthMode.FULL is the auth mode to check for since no other authorization mode requires
  //that users grant authorization
  if (authInfo.getAuthorizationStatus() === ScriptApp.AuthorizationStatus.REQUIRED) {
    return msg;
  } else {
    return "No Authorization needed";
  }
}
Run Code Online (Sandbox Code Playgroud)