【问题标题】:Why Apps Script execution failed only when it is triggered by onEdit event on Google Spreadsheet?为什么只有在 Google 电子表格上的 onEdit 事件触发时,Apps 脚本执行才会失败?
【发布时间】:2020-05-29 09:49:20
【问题描述】:

我正在研究 Google Apps 脚本。我有我编写的应用程序脚本,应该由特定工作表上的onEdit 事件执行。

onEdit.gs

function onEdit(e) {
    var syokuninIchiran = new SyokuninIchiran();
    syokuninIchiran.syncTable();
}

当在sheet上通过edit执行上述操作时,会出现这个错误:

您无权调用 openById。所需权限:https://www.googleapis.com/auth/spreadsheets

但是,当脚本从 Google Apps 脚本开发窗口触发时,它可以正常工作。我通过如下的测试函数调用相同的代码:

function test(){
  var syokuninIchiran = new SyokuninIchiran();
  syokuninIchiran.syncTable();
}

这个问题可能有问题?电子表格的所有者不是我的。我的帐户有权编辑如下图。

尝试1: 我尝试将范围手动添加到清单文件中(appsscript.json)。我批准了授权。但是,什么都没有改变。它仍然有相同的错误消息。

{
  "oauthScopes": [
    "https://www.googleapis.com/auth/sqlservice",
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/script.external_request"
    ]
}

【问题讨论】:

    标签: google-apps-script google-sheets-api


    【解决方案1】:

    答案:

    Simple Triggers 不能打开除了它所绑定的文件之外的文件。为此,您需要使用可安装的触发器。

    更多信息:

    根据Simple Trigger restrictions 上的文档:

    因为简单的触发器会自动触发,不需要用户授权,它们会受到一些限制:

    他们可以修改他们绑定的文件,但不能访问其他文件,因为这需要授权。

    因此必须使用可安装的触发器。

    设置可安装触发器:

    点击Edit > Current project's triggers 菜单项,这将在 G Suite 开发者中心打开一个新页面。点击右下角的+ Add Trigger按钮,进行触发设置如下:

    • 选择要运行的函数:onEdit
    • 选择应该运行的部署:Head
    • 选择事件源:From Spreadsheet
    • 选择基于时间的触发器类型:On Edit

    然后按保存。这将增加编辑触发器的功能范围。

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 2021-04-21
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      相关资源
      最近更新 更多