Google Script has two triggers for on edit. Can I remove the “simple” one?

限于喜欢 提交于 2021-01-29 15:09:49

问题


I have a Spreadsheet script with an onEdit trigger. For some reason two onEdit triggers are "fired": an installed trigger and a simple trigger. I set up onEdit to send an email. This was authenticated for the installed trigger and works fine. However, each time it fires the simple trigger it throws an exception. Is it possible to remove or disable the simple trigger so that it doesn't throw the exception?

I wrote a simple function to check what triggers my script was using. It only shows one onEdit trigger, even though it triggers both simple and installed.

function checkTriggers(){
  var triggers = ScriptApp.getProjectTriggers();

  triggers.forEach(function(trigger){console.log(trigger.getHandlerFunction())});
}

Screenshot of checkTriggers() output:


回答1:


Merge both onEdit triggers:

Assuming you have 2 onEdit triggers. One simple which is called onEdit(e) and one installable which is called myFunction(e). Since you have already authorized myFunction(e) and it is an installable trigger, you can rename your onEdit(e) simple trigger to a different name e.g. myFunction2(e) and put inside myFunction(e):

function myFunction(e){
  //code for the installable myFunction
  myFunction2(e) 
}

In this way both myFunction and myFunction2 will be triggered. If you want to remove myFunction2 altogether, then simply remove or comment out the code that relates to that.

Issue with the simple onEdit(e) trigger:

Remove the simple onEdit(e) trigger as it can't be used in your case because your script uses services that require authorization.

  • Change the name of the function from onEdit(e) to something else e.g. myFunction(e).

  • Create an installable onEdit trigger for myFunction.

  • To create an installable trigger for myFunction use this solution. Namely, execute the create_onEdit function:

    function create_onEdit(){
      ScriptApp.newTrigger('myFunction')
      .forSpreadsheet(SpreadsheetApp.getActive())
      .onEdit()
      .create(); 
    }
    

and make sure myFunction(e) lives in the same script editor.



来源:https://stackoverflow.com/questions/65799452/google-script-has-two-triggers-for-on-edit-can-i-remove-the-simple-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!