25
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
ctx.load(web);
var user = web.get_currentUser();
alert(user);

I used above code to get the current user using JavaScript, but I got an error:

'SP.ClientContext.get_current' is null or not an object

What should I do? Any help appreciated.

32

I have used SharePoint’s JavaScript Object Model to retrieve the current logged in username.Once you have executed the load and executeQueryAsync methods and the call to SharePoint was sucessful, then inside of the onQuerySucceeded method is where I display the username to the browser using the SP.Principal.get_loginName property. Try it out…you can host and run the code below inside of a content editor web part in SharePoint 2010.

<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(init,'sp.js');
var currentUser;
function init(){
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.clientContext.load(currentUser);
    this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}

function onQuerySucceeded() {
    document.getElementById('userLoginName').innerHTML = currentUser.get_loginName(); 
    document.getElementById('userId').innerHTML = currentUser.get_id();
    document.getElementById('userTitle').innerHTML = currentUser.get_title();
    document.getElementById('userEmail').innerHTML = currentUser.get_email();
}

function onQueryFailed(sender, args) {
    alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
</script>
<div>Current Logged User:
    <span id="userLoginName"></span>
    <span id="userId"></span>
    <span id="userTitle"></span>
    <span id="userEmail"></span>
</div>

or use the below code

function CallClientOM()
{
var context = new SP.ClientContext.get_current();
this.website = context.get_web();
this.currentUser = website.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}



function onQuerySucceeded(sender, args)
 {
 alert(currentUser.get_loginName());
 }



function onQueryFailed(sender, args)
{
alert('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());
}
  • i tried your code, but got an error it showed "Sys.ArgumentUndefinedException: Value cannot be undefined. Parameter name: method" – Nera Jul 18 '13 at 18:22
  • @Karthik-Jaganathan: This is exactly what I needed. Are there other properties I can get? Like department and phone number? – IMTheNachoMan Nov 19 '15 at 0:54
  • Karthik i am trying to run this script in Anynomous Mode where everyone has view access to the script library. But i get "Access Denied: You do not have permission to perform this action or access this reources". Is there any way i can run this when page loads when site is public? – allegro octopus Apr 19 '16 at 15:34
8

I normally use this function below. You can modify it depending on how you want to use it.

function getUserInformation(){
   var context = new SP.ClientContext.get_current();
   var web = context.get_web();  
   var currentUser = web.get_currentUser();  
   currentUser.retrieve();
   context.load(web);
   context.executeQueryAsync(
      function(){ //On success function
        var userObject = web.get_currentUser();
        var email = userObject.get_email();
        var id = userObject.get_id();
        var loginName = userObject.get_loginName();
        console.log(userObject);

     },
     function(){ //On fail function
        alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
     }
  );
}
3

I have used below JavaScript function to get login name of current logged in user.

While working on this code, it was noticed that get_loginName() function brought i:0#.w|DomainName\asad. So I have used string manipulation to get the desired one i.e. DomainName\asad

function getCurrentUser() {
    try {
        var clientContext = new SP.ClientContext.get_current();
        var tempcurrentUser = clientContext.get_web().get_currentUser();
        clientContext.load(tempcurrentUser); 
        clientContext.executeQueryAsync(function() {

            //If you notice tempcurrentUser will contain 
            //something like this i:0#.w|DomainName\asad. 
            //But we would want only DomainName\asad, so we use string manipulation

            var index = tempcurrentUser.get_loginName().indexOf('|') + 1;
            var currentUser = tempcurrentUser.get_loginName().substring(index);

            // Here you will get the desired login name 
            // of current logged in user i.e. DomainName\asad
            alert(currentUser);

        }, Fail);
    } catch (err) {
        Fail();
    }
}

function Fail() {
    alert("error");
}
  • 1
    Note: May require SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.js'); above it. – vapcguy Mar 7 at 19:16
2

You can get logged in user name/id by using

  • _spPageContextInfo.userId
  • _spPageContextInfo.userLoginName

Hope it helps someone.

  • 5
    AFAIK _spPageContextInfo.userLoginName is available in SharePoint Online, and not in On Premise. – Asad Refai Nov 18 '15 at 5:39
  • FYI, _spPageContextInfo.userId gives a number, not the user's actual user name, btw. – vapcguy Mar 7 at 18:39
2

'SP.ClientContext.get_current' is null or not an object

You are trying to access 'SP.ClientContext' while libraries are being loaded. So use this line of code to wait until the library is loaded.

SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.js');

SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.js');

function getCurrentUser() {
        var context = new SP.ClientContext.get_current();
        var web = context.get_web();
        currentUser = web.get_currentUser();
        context.load(currentUser);
        context.executeQueryAsync(onSuccess, onFail);
}

function onSuccess(sender, args) {
        var acountname = currentUser.get_loginName(); // extract the login name from the account name
        // var username = currentUser.get_title(); 
}

function onFail(sender, args) {
        alert('Failed to get current user' + args.get_message());
}

Or use REST API

function getUser() {
    var userid = _spPageContextInfo.userId;
    //alert(userid);

    var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
    var requestHeaders = { "accept": "application/json;odata=verbose" };
    $.ajax({
        url: requestUri,
        contentType: "application/json;odata=verbose",
        headers: requestHeaders,
        success: onSuccess,
        error: onError
    }); function onSuccess(data, request) {
        var loginName = data.d.Title;
        alert(loginName);
    } function onError(error) {
        alert("Error on retrieving current user.");
    }
}
  • 1
    url part for current user is '/_api/web/CurrentUser' – Chris DS Oct 12 '18 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.