user12736831
user12736831

Reputation:

Install user specific onEdit Trigger using Google Apps Script

I have created a simple OnOpen add-on in Google sheets that installs a trigger to send email based on Edit in the sheet. When I installed it, I authorized it from my account. The script is as follows:

function onOpen(e) {
  
  var ui = SpreadsheetApp.getUi().createMenu("Install Trigger").addItem("Run", "initialize").addToUi();
 }
 
const initialize = () => {
  
     var ss = SpreadsheetApp.getActiveSpreadsheet();
  
     ScriptApp.newTrigger('sendEmail')
    .forSpreadsheet(ss)
     .onEdit()
     .create();
};

The script runs fine and sends emails from my email address which I authorized. Now the issue is when I shared this sheet with another editor, the person does not need to install this trigger and he can send email from my email account without any authorization. Is there a way that we can make every editor in this sheet install their own trigger to send email from their email account instead of using mine?

Upvotes: 0

Views: 983

Answers (1)

Kessy
Kessy

Reputation: 2004

You could use the method getUserTriggers(spreadsheet) that retrieves all installable triggers owned by the user executing the script:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var triggers = ScriptApp.getUserTriggers(ss);
// Log the event type for the first trigger in the array.
Logger.log(triggers[0].getEventType());

If this comes with a trigger, you know that the user has already installed the trigger.

If this comes empty, means that the user has no triggers in it. Then you could use the method deleteTrigger(trigger) to delete the existing triggers (created by others) in the script and then programatically create a new one:

var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++) {
  ScriptApp.deleteTrigger(triggers[i]);
}

Upvotes: 0

Related Questions