Search code examples
google-apps-scriptweb-applications

google script Session.getActiveUser().getEmail() not working


I've developed a web app with google script and code this in my gs.

var email = Session.getActiveUser().getEmail();
Logger.log(email);
// then do something to render the Email address on the page

After publishing the script, I log in with another account and execute the script.

Then the page display this:

This application was created by another user, not by Google.

This application has access to the following personal information: email address.

But still nothing in Log and the page display nothing.

I just don't get it...


Solution

  • Although it's not stated explicitly in the reference documentation for Session.GetActiveUser(), my testing confirmed that your web app needs to execute as the user accessing the web app to have access to getActiveUser(). I used the code below and the logging library described here.

    Depending on the use case of your application, perhaps you could create a library containing a centralized ScriptDB instance to capture the active user email. Then, create another project that works with your private spreadsheet and the same scriptDB library.

    var LOG_FILENAME = 'your-log-doc'
    var LOG_PATH = 'folder/subfolder/third-folder'
    
    
    function doGet() {
      //Change variable above to a good path and filename for you
      var x = LogLibrary.InitializeLogging(LOG_PATH, LOG_FILENAME)
      Logger.log(x)
    
      var email = Session.getActiveUser().getEmail();
      Logger.log("Start email logging")
      Logger.log(email);
      LogLibrary.fnSaveLog()  //Write the save and flush the logger content
    
      // then do something to render the Email address on the page
      var HTMLToOutput = '<html><h1>A header</h1><p>' + email + '</p></html>';
      return HtmlService.createHtmlOutput(HTMLToOutput);
    }