Based on Session.getActiveUser(),
If security policies do not allow access to the user's identity, User.getEmail() returns a blank string.
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)
Hence, you need to use an installable trigger which can call services that requires authorization.
Sample Configuration:
Sample Code:
Code.gs
function onOpen(e) {
showSidebar();
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var email = e.user.getEmail();
body.appendParagraph(email);
body.appendParagraph(Session.getActiveUser().getEmail());
}
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('Page')
.setTitle('My custom sidebar');
DocumentApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showSidebar(html);
}
function getActiveUser(){
var email = Session.getActiveUser().getEmail();
Logger.log(email);
return email;
};
I used 2 different ways to get the active user, 1.) Using the onOpen() event object e.user.getEmail()
, and 2.) Using Session.getActiveUser().getEmail()
.
Both options were able to display the active user's email as seen in the document where email was appended as paragraph.
Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="rangeResult"></div>
<script>
function addRange(rangeStartEnd){
$('#rangeResult').text(rangeStartEnd);
};
google.script.run.withSuccessHandler(addRange).getActiveUser();
</script>
</body>
</html>
Output:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…