可以以编程方式创建触发器吗

可以以编程方式创建触发器吗

本文介绍了onEdit 可以以编程方式创建触发器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的脚本,试图通过 onEdit 函数以编程方式创建一个脚本

I wrote a simple script trying to programmatically create a script from the onEdit function

function onEdit() {
  test();
}

function test() {
  triggerLater();
}

function customMsgBox() {
  Browser.msgBox("hello world");
}

function triggerLater() {
  var date = new Date();
  date.setMinutes(date.getMinutes() + 1);
  try {
    var oneTimeOnly = ScriptApp.newTrigger("customMsgBox")
      .timeBased()
      .at(date)
      .create();
    return oneTimeOnly.getUniqueId();
  }
  catch (e) {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    ss.toast("error");
  }
}

如果我尝试从脚本编辑器运行 onEdit,则会创建触发器,但电子表格上的每次编辑都会在 toast

If I try to run onEdit from the script editor the trigger is created but every edit on the spreadsheet get a "error" message in a toast

有人可以帮我理解吗?

推荐答案

onEdit 简单的事件处理函数具有有限的权限(即它不能发送电子邮件、打开日历等).因为它在没有用户权限的情况下运行.因此,它不能设置触发器(没有任何限制,这将是一个巨大的安全漏洞).

The onEdit simple event handler function has limited permissions (i.e. it can not send emails, open the calendar, etc). Because it runs without the users permissions. Therefore, it can not set up a trigger (which do not have any restrictions and would be a huge security bug).

如果您希望触发器应在您的帐户下创建,请使用可安装的编辑触发器.首先,将您的 onEdit 函数重命名为其他名称(因此它不会作为简单的事件处理程序触发),然后转到资源"菜单并选择您的函数以在电子表格编辑事件上运行.查看文档了解更多信息.

If you expected that the trigger should be created under your account, use the installable on edit trigger. First, rename your onEdit function to something else (so it is not triggered as a simple event handler), then go to the Resources menu and pick your function to run on spreadsheet edit events. Take a look at the docs for more.

这篇关于onEdit 可以以编程方式创建触发器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 12:15