11

I tried this code:

  var context = new SP.ClientContext.get_current();

  this.website = context.get_web();

  this.currentUser = website.get_currentUser(); 

  alert(currentUser);

But I got an alert and it shows "[object object]".

How to get the loginName of current user? Any help appreciated.

1

6 Answers 6

22

If you are working on SharePoint Online, then they have introduced a new variable to hold the current user's login name in the _spPageContextInfo global object.

_spPageContextInfo.userLoginName;

This will get you the login name without making any AJAX calls with JSOM or REST.

3
  • 4
    I just tried that in 2013 and it's undefined. SharePoint Online here. _spPageContextInfo.userId works, though, and is a good starting point.
    – Geeky Guy
    Jan 15, 2014 at 14:47
  • 1
    Yup it won't be available everywhere as they would be updating the API gradually. Jan 15, 2014 at 17:10
  • It worked for me. thank you so much! I gave you an upvote :) Apr 15, 2020 at 12:02
12
function GetCurrentUsername()
{
    var ctx = new SP.ClientContext.get_current();
    this.website = ctx.get_web();
    this.currentUser = website.get_currentUser();
    ctx.load(currentUser);
    ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFail));
}

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

function onFail(sender, args)
{
    alert('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());
}
5

It shows [object object] in your alert message because you are trying to display an object instead of its properties. [Object object] is the default serialization of an object in JavaScript.

You can use JSOM or REST API to get current user as follows

JSOM

 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());
    }

using REST API // for SharePoint 2013

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.");
    }
}
3

You never load any objects and never executes the query so there is no wonder you get an error.

Do something like:

var clientContext = SP.ClientContext.get_current();
var website = clientContext.get_web();
currentUser = website.get_currentUser();
clientContext.load(website);
clientContext.load(currentUser);
   clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);

function onRequestSucceeded() {
    alert(currentUser.LoginName);
}

function onRequestFailed(sender, args) {
    alert('Error: ' + args.get_message());
}

Where website and currentUser are declared in the outer function (encapsuling the onRequestSucceeded method)

With reservation for errors in the code (are writing this from my phone)

-1

Try this:

alert(currentUser.get_loginName());

Reference: Working with users using javascript

4
  • i tried your code it gives "Undefined" instead of "[object object]"
    – Nera
    Jul 18, 2013 at 18:29
  • Updated answer...
    – BlueBird
    Jul 18, 2013 at 18:44
  • I tried this as well. It gave me bellow error "The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested." Does this imply about a referencing issue ??
    – Nera
    Jul 19, 2013 at 4:34
  • 1
    No it implies exactly what both myself and pushpendra have answered you, that you are not loading objects or executing the query :) Jul 19, 2013 at 5:09
-2
String userName=string.Empty;
using (SPSite osite = new SPSite(SPContext.Current.Web.Url))
{
    using (SPWeb oweb = osite.OpenWeb())
    {
        if (oweb.CurrentUser != null)
        {
            if (oweb.CurrentUser.LoginName.Contains("\\"))
            {
             string[] usernameLogged = oweb.CurrentUser.LoginName.Split('\\');
                if (usernameLogged.Length > 0)
                {
                    userName = usernameLogged[1].ToString();
                }
            }
        }
    }
}
1
  • 3
    This is server side code, the question clearly mentions It should be done in JavaScript. Dec 1, 2015 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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