Reputation:
This will hopefully be an easy one for you experienced developers. I'm trying to use the Google Apps Script service to get the username of the logged in user for my Google Site. I can get the email to display fine, however when I try to use the substring method to shorten to the username I get the follow error.
TypeError: Cannot find function substring in object [email protected]. (line 4, file "getusername")
I understand why I'm getting this error but not sure how to fix it. Below is my code
function doGet() {
var userEmail = Session.getEffectiveUser();
var username = userEmail.substring(0, userEmail.indexOf("@"));
var HTMLString= "<body> <h2> Logged in as " + userEmail +",</h2></body>";
HTMLOutput = HtmlService.createHtmlOutput(HTMLString);
return HTMLOutput
}
I'm guessing that because the variable userEmail
is dynamic depending on the logged in user, the variable username
is unable to see the email address until it has executed ?
Any help would be greatly appreciated.
Complete Javascript newbie here.
Thanks
Jack
Upvotes: 1
Views: 4563
Reputation: 31300
Change:
var userEmail = Session.getEffectiveUser();
to:
var userEmail = Session.getEffectiveUser().getEmail();
If you look at the documentation for Session.getEffectiveUser()
, you'll see what the "return" is. I never paid much attention to that for a long time. But, you need to always know what is returned. Some return types are: string, or an object, or an integer, or a Class. Depending upon what is returned, that will determine what you can further do. Lots of beginners notice that there is a period in between things, and are able to figure out that they need to patch things together with a period. But they don't really know what that period is for. That period is called a dot operator, and every place there is a "dot operator" is basically another step in a process. You're "chaining" multiple operations together. In the code: Session.getEffectiveUser().getEmail()
there are two periods (dot operators) and two separate things happening, each with a different returned value. The getEmail()
method returns a string. The documentation states that getEffectiveUser()
returns a "User" But if you go to the documentation for "User" you'll see it described as a "Class". To understand what a "Class" is, you'll need to do some research.
Upvotes: 2