Fetching a User Using the SharePoint CSOM (via JavaScript)

I tend to need to do this sort of thing a lot recently, and it’s not as simple as looking for a pre-fetched value sitting in the DOM somewhere, so I figured I better blog it and then I’ll know where to find it.

Here’s my code (below). All you have to do is call “retrieveUser()”. Eventually, either the “onUserQuerySucceeded” or “onUserQueryFailed” callback will be called (by the system), and you’ll have your answer. Note in the onUserQuerySucceded method, I break apart the loginName (both claims and non-claims values should work for this) and extract just the username portion (so “domain\bob” should return “bob” as well as “i:0#.w|domain\bob” should return “bob”).


var oItgCurrentUser = null;
var sItgCurrentUserLoginName = "";
 

function retrieveUser()
{
var clientContext = new SP.ClientContext.get_current();
var oWeb = clientContext.get_web();
oItgCurrentUser = oWeb.get_currentUser();
clientContext.load(oItgCurrentUser);
clientContext.executeQueryAsync(Function.createDelegate(this,this.onUserQuerySucceeded), Function.createDelegate(this,this.onUserQueryFailed));
}

 

function onUserQuerySucceeded(sender, args)
{
sItgCurrentUserLoginName = oItgCurrentUser.get_loginName();
var position = sItgCurrentUserLoginName.indexOf("\\");

if (position >= 0)
{
sItgCurrentUserLoginName = sItgCurrentUserLoginName.substr(position + 1);
} //OPTIONAL IF YOU WANT JUST THE USERNAME AFTER THE DOMAIN
}

 

function onUserQueryFailed(sender, args)
{
//   alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

I used this link as a reference to build my own solution:

http://sharepoint.stackexchange.com/questions/73032/get-current-user-in-client-object-model-with-javascript