Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

google apps script - onEdit can programmatically create a trigger?

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");
  }
}

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

Can someone help me to understand ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...