MAbig11
MAbig11

Reputation: 51

How do I keep Google Appscript triggers when a copy is made of a sheet?

I've got a master spreadsheet which people will regularly be making copies of. I've got several on edit triggers set up on the master but can't seem to keep these working on copies of the spreadsheet. Is there any way to resolve this?

Upvotes: 0

Views: 2122

Answers (2)

Divyanshu Agnihotri
Divyanshu Agnihotri

Reputation: 11

to add to what ziganotschka is saying.

we can add installable triggers in the script itself and get them installed with onOpen trigger.

one time authorization is required for these to run, for that you can create a button on the google sheet and assign onOpen function to it.

once that is clicked authorization will happen. and you shall be good to go.

Now the problem is if we ask the sheet to install trigger onOpen it will keep on installing triggers everytime the sheet opens.

a simple if logic can be a work around.

example code :

    function onOpen() {

makeTriggerIfempty();
       
}


function makeTriggerIfempty() {
  
  var allTriggers = ScriptApp.getProjectTriggers();

  if(allTriggers.length < 1){

  createTimeDrivenTriggers();

  }
}

function createTimeDrivenTriggers() {
  // Trigger every 2 hours.
  ScriptApp.newTrigger('myFunction')
      .timeBased()
      .everyHours(2)
      .create();

  // Trigger every Monday at 08:00.
  ScriptApp.newTrigger('myFunction')
      .timeBased()
      .onWeekDay(ScriptApp.WeekDay.MONDAY)
      .atHour(8)
      .create();
}

Upvotes: 1

ziganotschka
ziganotschka

Reputation: 26796

  • Installable triggers apply to the spreadsheet to which they were bound
  • Simple triggers are defined in the script
  • When you make a copy of a spreadsheet, the bound Apps Script will also be copied
  • Thus, the simple onEdit triggers contained in the script will also get copied and will work for the copied spreadsheet
  • All the users have to do is to run the script once manually - in order to trigger authorization flow

Upvotes: 0

Related Questions