0
votes

Overview

Im making a script for my google sheet.

I have a helper method which takes email for parameter (string) and then invites that email to google drives folder.

I also have edit() function which gets called whenever a field in Google Sheets is changed.


Problem:

When helper method is called by itself from Google Scripts it works fine and I get an invite. When helper method is triggered from edit() while im in google sheets, it doesn't go all the way through to send an invitation. It stops at while function which returns false:

 var newFolder = DriveApp.getFoldersByName("New Folder");
  Logger.log(newFolder.hasNext());
  while(newFolder.hasNext()) {      -> returns false while in google sheets
    var folder = newFolder.next();
    Logger.log("folder -> " + folder);  
    folder.addViewer(newPersonEmail);
  } 

What I tried:

Logger.log shows that newFolder.hasNext() returns false while script gets called from edit() function (when im making a change in google sheets). But it returns true when I simply debug function in Google scripts.

1

1 Answers

1
votes

You have to register edit() for the specific user. It's not possible for the simple onEdit trigger.

It returns false because there is nothing for the current user. And it's true.

===== Updated =====

As for me, I think It's normal to create a triggers for users every time when we needs their scopes. Suppose we need to force a user to register a trigger. He has to run regTrigger()

/**
 * @param {GoogleAppsScript.Events.SheetsOnEdit} e
 */
function edit(e) {
  // there is the edit eveng action
}

/**
 * Register trigger
 * @returns {GoogleAppsScript.Script.Trigger}
 */
function regTrigger() {
  var activeSpreadsheet = SpreadsheetApp.getActive();
  var triggers = ScriptApp.getUserTriggers(activeSpreadsheet).filter(function(
    trigger
  ) {
    return (
      trigger.getEventType() === ScriptApp.EventType.ON_EDIT &&
      trigger.getHandlerFunction() === 'edit'
    );
  });

  if (triggers.length) return triggers[0];

  return ScriptApp.newTrigger('edit')
    .forSpreadsheet(activeSpreadsheet)
    .onEdit()
    .create();
}

Now your task is to give the user the opportunity to perform this function once (regTrigger). For example, from the menu. Or make it happen when you open the Table forcing some events.