Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...