Defining the current user in Script applications

I am trying to identify the current username in order to take notes about who edited something like this:

  r.setComment("Edit at " + (new Date()) + " by " + Session.getActiveUser().getEmail());

but this will not work - username is an empty string. Where am I wrong?

+7
source share
4 answers

GOOD NEWS: It is possible with this workaround!

I use some security features that show the user and owner of the document, and I store it in properties for better performance. Enjoy it!

function onEdit(e) {
  SpreadsheetApp.getUi().alert("User Email is " + getUserEmail());
}

function getUserEmail() {
  var userEmail = PropertiesService.getUserProperties().getProperty("userEmail");
  if(!userEmail) {
    var protection = SpreadsheetApp.getActive().getRange("A1").protect();
    // tric: the owner and user can not be removed
    protection.removeEditors(protection.getEditors());
    var editors = protection.getEditors();
    if(editors.length === 2) {
      var owner = SpreadsheetApp.getActive().getOwner();
      editors.splice(editors.indexOf(owner),1); // remove owner, take the user
    }
    userEmail = editors[0];
    protection.remove();
    // saving for better performance next run
    PropertiesService.getUserProperties().setProperty("userEmail",userEmail);
  }
  return userEmail;
}
+12
source

I suppose you have this piece of code to execute inside a function onEdit(or trigger when editing).

, Session.getActiveUser().getEmail() . , Google.

+5

Wim den Herder, , . script . , script . , :

When the user uses the sheet for the first time, when he / she has to click a button and run this:

function identifyUser(){
   var input = Browser.inputBox('Enter User Id which will be used to save user to events (run once)');
  PropertiesService.getUserProperties().setProperty("ID", input);
}

This saves user input to the user property. It can be read later at any time using this code:

var user = PropertiesService.getUserProperties (). getProperty ("ID");

+1
source
function onEdit(e) {
  SpreadsheetApp.getUi().alert("User Email is " + e.user);
}
-2
source

All Articles