Determine current user in Apps Script

GOOD NEWS: It’s possible with this workaround!

I’m using some protection functionality that reveals the user and owner of the document and I’m storing it in the properties for better performance. Have fun with 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;
}

Leave a Comment