anielsen
anielsen

Reputation: 21

Google Apps Scripts getFirstName and getGivenName error

I am working in Google Apps Script trying to pre-populate a field with the currently logged in users first name and last name. According to Google's documentation I should be able to get this with getGivenName() and getFamilyName(). When I include those using the following code:

  var myFirstName = Session.getEffectiveUser().getGivenName();
  var myLastName = Session.getEffectiveUser().getFamilyName();

I get the following errors:

TypeError: Cannot find function getGivenName in object
TypeError: Cannot find function getFamilyName in object

On the other hand, this code works:

var myEmail = Session.getEffectiveUser().getEmail();
var myUsername = Session.getEffectiveUser().getUsername();

Are these functions not yet implemented?

Upvotes: 2

Views: 4284

Answers (1)

Serge insas
Serge insas

Reputation: 46822

The doc you refer to is about UserManager which is a part of the Domain Service only available with a Google Apps account in a domain... nothing to do with Session.getEffectiveUser() that is part of the Base service.

You could use the autocomplete feature to avoid such confusion.

EDIT : for info : if the logged user is in your contacts, then you can retrieve whatever is in there. Example code with comments:

function getUserInfo(){
   var email = Session.getEffectiveUser().getEmail();
   var userName = Session.getEffectiveUser().getUsername();
Logger.log(email+'  '+userName)
   if(ContactsApp.getContact(email)){ ;// if the logged user is in your contacts
     var fullName = ContactsApp.getContact(email).getFullName();// there a quite a few parameters available from here
     var nickName = ContactsApp.getContact(email).getNickname();// these are just examples
     var tel =  ContactsApp.getContact(email).getPhones();// returns an array of phones object
     var telnums=[]
      for(var t in tel){telnums.push(tel[t].getLabel()+"="+tel[t].getPhoneNumber())} ;// get the numbers ans store in an array
Logger.log(fullName+' / '+nickName+' / phone :'+telnums.join(' & ')) ;// join the array for proper display
   }
}

EDIT 2 : following your comment : FOR GOOGLE APPS ACCOUNT , this code is working to get user information, see doc here, you have to get the user object

function getUserInfo(){
   var email = Session.getEffectiveUser().getEmail();
   var userName = Session.getEffectiveUser().getUsername();
Logger.log(email+'  '+userName)
   var user = UserManager.getUser(userName);// get the user object
   var firstName = user.getGivenName();// from there get whatever you want that is available (see autocomplete, not so much possibilities...)
   var familyName = user.getFamilyName();
  Logger.log(firstName+' / '+familyName)
}

Note : before using this script you have to authorize this API :

enter image description here

Upvotes: 1

Related Questions