onEdit trigger doesn't catch current user

2019-08-18 06:03发布

I'm trying to build a simple log for sheets that makes use of cell notes. Somehow i can't include the email of the user who triggers the onEdit-event.

function onEdit(e){
    var email = Session.getActiveUser().getEmail();
    var date = String(Utilities.formatDate(new Date(), 'Europe/Berlin', 'HH:mm dd/MM/yy'));
    var range = e.range;
    range.setNote(email + " @ " + date);
}

The note appears on the cell but the email is empty. Could that have to do with missing permissions? I assume if something would be wrong with my code the note wouldn't appear at all on the edited cell in sheets...

1条回答
在下西门庆
2楼-- · 2019-08-18 06:12

Here's what Google documentation says about the Session class

The Session class provides access to session information, such as the user's email address (in some circumstances) and language setting.

In regards to 'getActiveUser()' method, it states

If security policies do not allow access to the user's identity, User.getEmail() returns a blank string. The circumstances in which the email address is available vary: for example, the user's email address is not available in any context that allows a script to run without that user's authorization, like a simple onOpen(e) or onEdit(e) trigger, a custom function in Google Sheets, or a web app deployed to "execute as me" (that is, authorized by the developer instead of the user). However, these restrictions generally do not apply if the developer and the user belong to the same G Suite domain.

Because you use the simple trigger - onEdit() - the code will not execute unless explicitly authorized by the user. For installable triggers, that would mean executing the function manually from the script editor.

You can publish the project as a sheets add-on. In this case, users will be asked to grant permissions declared in the add-on manifest.

More info https://developers.google.com/apps-script/reference/base/session

查看更多
登录 后发表回答