Wednesday, May 4, 2016

How to get user’s login name in Sharepoint Online via javascript object model

In this post I will show how to achieve simple task: get login name of the user via javascript object model. The main misleading thing is that in current version of MSDN documentation SP.User object contains only the following properties:

- email
- groups
- isSiteAdmin
- userId

You might think that email property can be used as login name (because in Sharepoint Online users are authenticated using their email – organizational or external connected to MS live id). However some time ago the following note was added to this property in MSDN:

This property is not available in SharePoint Online.

So how to get login name then? The answer is to use not-documented loginName property which will return you login name of the user in claims format. E.g. the following example shows how to get login name of the current user via javascript object model in Sharepoint Online:

   1: var ctx = SP.ClientContext.get_current();
   2: var currentUser = ctx.get_web().get_currentUser();
   3: ctx.load(currentUser);
   4:  
   5: ctx.executeQueryAsync(
   6:     Function.createDelegate(this, function (sender, args) {
   7:         console.log("Login name: " + currentUser.get_loginName());
   8:     }),
   9:     Function.createDelegate(this, function (sender, args) {
  10:         console.log("Error: " + args.get_message()
  11:     }));

Hope that this information will help someone.

1 comment:

  1. Note that in some cases the login name is not the same as user's email address. It can be different even in O365 environment.

    ReplyDelete