Search code examples
google-apps-scriptweb-applications

How to capture the user of the web app from the front end


I am using

var user = Session.getActiveUser().getEmail();

in a script on the frontend before form submission but that throws an error:

Session is not defined

The webapp will run as the owner of the script not as the user so I can't use the code in the backend script. Is there a frontend call that will get the user name or do I have to make them tell me? This app is one from within the domain so it should be somewhat trusted.


Solution

  • Session.getActiveUser() will return the current user's email address assuming they are on the same domain.

    Gets information about the current user. 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 runs the script themselves or belongs to the same G Suite domain as the user.

    Session.getEffectiveUser() will, on the other hand, return the user the web-app is set to execute as.

    Gets information about the user under whose authority the script is running. If the script is a web app set to "execute as me" (the developer), this returns the developer's user account. If the script is running under an installable trigger, this returns the account of the user who created the trigger. In most other scenarios, this returns the same account as getActiveUser().

    So if you need the user's email on the front-end you'll have to get it on the back-end using Session.getActiveUser() and pass it to the front-end via scriptlets when you .evaluate(), or call a server-side function from client-side JavaScript, via google.script.run.