Home > Enterprise >  How to pass event object to .onChange() trigger in Google Apps Script
How to pass event object to .onChange() trigger in Google Apps Script

Time:05-04

I'm trying to add a trigger to my Google Sheet so that a certain function is run (say for example an alert is to ui) when any sheets are renamed.

I found the following post that explains a workaround Event on rename worksheet tab not triggered but I'm not sure if this will actually work because it is not what document this listener is supposed to listen to.

From my previous experience writing successful even triggers for Google Forms we have to use a trigger builder like the following example. Now if I want to pass the event to myFunction in the following code how do I do it?

let currentSs = SpreadsheetApp.getActive();

ScriptApp.newTrigger('myFunction')
.forSpreadsheet(currentSs)
.onChange()
.create();

function myFunction() {
 if event.changeType === 'Other' {
  //do this
 }
}

CodePudding user response:

Try this:

function createTrigger() {
  if (ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() == "myFunction").length == 0) {
    ScriptApp.newTrigger("myFunction").forSpreadsheet(SpreadsheetApp.getActive()).onChange().create();
  }
}

function myFunction(e) {
  if (e.changeType == 'OTHER') {
    //do this
  }
}
  • Related