30

How to get current user name using JavaScript in Script Editor web part?

Laurel
  • 5,965
  • 14
  • 31
  • 57
Kate
  • 1,495
  • 4
  • 21
  • 35

12 Answers12

37

Here is the code that worked for me:

<script src="/SiteAssets/jquery.SPServices-2013.02a.js" type="text/javascript"></script>
<script src="/SiteAssets/jquery.js" type="text/javascript"></script>

<script type="text/javascript">
  var userid= _spPageContextInfo.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");
  }
</script>
Kate
  • 1,495
  • 4
  • 21
  • 35
  • 1
    very useful for acquiring the Web User information. – GoldBishop Mar 24 '14 at 17:19
  • 1
    If you use SP2010 like me, it won't work for you because `_spPageContextInfo.webAbsoluteUrl` doesn't work on SP2010. check [here](http://sympmarc.com/2013/03/26/using-_sppagecontextinfo-to-determine-the-current-sharepoint-context-in-script) – mohsenof Nov 06 '14 at 10:31
  • This worked for me too, thanks ! I couldn't use the ClientContext object, as it does not triggered any errors, but the JS process was blocked to creation of the ClientContext. – Alex Nov 20 '14 at 14:57
  • i'm getting this JS error. _Uncaught ReferenceError: L_Menu_BaseUrl is not defined_ – CidaoPapito Feb 11 '15 at 12:58
  • If you're using a script editor webpart, you can just use `_spPageContextInfo.userDisplayName` or `_spPageContextInfo.userDisplayName` to get the username or email address. – jdgregson Jun 27 '17 at 17:08
  • this code need admin permossion. i want to show login name to every client. – Seyed Reza Dadrezaei Dec 23 '19 at 09:07
22

I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.

//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
context.executeQueryAsync(function(){
    alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
}, function(){alert(":(");});

Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.

Lzh
  • 3,585
  • 1
  • 22
  • 36
16

If you are in a SharePoint Page just use:

_spPageContextInfo.userId;
Juan Maya
  • 180
  • 1
  • 8
  • 1
    The request was to get the username. This just returns the user-id. – Peter Mar 10 '16 at 07:53
  • 1
    If you're using a script editor webpart, you can just use _spPageContextInfo.userDisplayName or _spPageContextInfo.userDisplayName to get the username or email address. – jdgregson Jun 27 '17 at 17:09
  • Some of the properties dont work depending on your version of SPS: see https://webcache.googleusercontent.com/search?q=cache:J_Aj2w4ZgIcJ:https://info.summit7systems.com/blog/know-your-office-365-and-sharepoint-2016-_sppagecontextinfo+&cd=1&hl=en&ct=clnk&gl=au – Jeremy Thompson Nov 16 '19 at 00:06
14

How about this:

$.getJSON(_spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser")
.done(function(data){ 
    console.log(data.Title);
})
.fail(function() { console.log("Failed")});
brroshan
  • 1,640
  • 17
  • 19
4

You can use the SharePoint JSOM to get your current user's account information. This code (when added as the snippet in the Script Editor web part) will just pop up the user's display and account name in the browser - you'll want to add whatever else in gotAccount to get the name in the format you want.

<script type="text/javascript" src="/_layouts/15/SP.js"></script>
<script type="text/javascript" src="/_layouts/15/SP.UserProfiles.js"></script>
<script type="text/javascript">

  var personProperties;

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

  function getCurrentUser() {
    var clientContext = new SP.ClientContext.get_current();
    personProperties = new SP.UserProfiles.PeopleManager(clientContext).getMyProperties();
    clientContext.load(personProperties);
    clientContext.executeQueryAsync(gotAccount, requestFailed);
  }

  function gotAccount(sender, args) {
    alert("Display Name: "+ personProperties.get_displayName() + 
        ", Account Name: " + personProperties.get_accountName());
  }

  function requestFailed(sender, args) {
    alert('Cannot get user account information: ' + args.get_message());
  }

</script>

See the SP.UserProfiles.PersonProperties documentation in MSDN for more info.

Dorrene Brown
  • 619
  • 1
  • 6
  • 13
  • Maybe its just me, but i could not get this to work with ClientWebApp's. Started with a clean slate, and reverifying. Which deployment patterns would this design be best suited for? In regards to Auto, SharePoint, or Provider hosted WebApps. – GoldBishop Mar 24 '14 at 18:27
  • This code was written for a script editor web part -- are you trying to implement the same thing in an app for SharePoint? If so, the code would be a little different as you wouldn't have the same context that a script editor web part has. – Dorrene Brown Apr 01 '14 at 03:08
  • Actually, i was able to get the User from a WebApp, just the same as the Script Editor. The Context, should always be the same, just depends which door you open to get it. Think of the context just like the EF context framework. Having other issues, related to WebApp and cross-domain. Back burnered that development and implemented a WebPart, to get what i need done until we can resolve the x-domain. – GoldBishop Apr 01 '14 at 12:28
  • This is the right approach to get even custom properties that are added to the user profile later. Use `personProperties.get_userProfileProperties()` to get a full object with all properties, including the custom ones that cannot be gotten by using a getter function on it. – Martin Braun Nov 13 '17 at 12:59
4

To get current user info:

jQuery.ajax({
    url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser",
    type: "GET",
    headers: { "Accept": "application/json;odata=verbose" }
}).done(function( data ){
    console.log( data );
    console.log( data.d.Title );
}).fail(function(){
    console.log( failed );
});
Amit Bhagat
  • 4,182
  • 3
  • 23
  • 24
1

U can use javascript to achive that like this:

function loadConstants() {

    this.clientContext = new SP.ClientContext.get_current();
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();  
    this.clientContext.load(currentUser);
      completefunc:this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));


}

//U must set a timeout to recivie the exactly user u want:

function onQuerySucceeded(sender, args) {

    window.setTimeout("ttt();",1000);
}
function onQueryFailed(sender, args) {

    console.log(args.get_message());
}

//By using a proper timeout, u can get current user :

function ttt(){ 

    var clientContext = new SP.ClientContext.get_current();
    var groupCollection = clientContext.get_web().get_siteGroups();
    visitorsGroup = groupCollection.getByName('OLAP Portal Members');

    t=this.currentUser .get_loginName().toLowerCase();

    console.log ('this.currentUser .get_loginName() : '+ t);      

}
1

I had to do it using XML, put the following in a Content Editor Web Part by adding a Content Editor Web Part, Edit the Web Part, then click the Edit Source button and paste in this:

<input type="button" onclick="GetUserInfo()" value="Show Domain, Username and Email"/> 

<script type="text/javascript">
function GetUserInfo() {

$.ajax({
    type: "GET",
    url: "https://<ENTER YOUR DOMAIN HERE>/_api/web/currentuser",
    dataType: "xml",

    error: function (e) {
        alert("An error occurred while processing XML file" + e.toString());
        console.log("XML reading Failed: ", e);
    },

    success: function (response) {
        var content = $(response).find("content");
        var spsEmail = content.find("d\\:Email").text();
        var rawLoginName = content.find("d\\:LoginName").text();
        var spsDomainUser = rawLoginName.slice(rawLoginName.indexOf('|') + 1);
        var indexOfSlash =  spsDomainUser.indexOf('\\') + 1;
        var spsDomain = spsDomainUser.slice(0, indexOfSlash - 1);
        var spsUser = spsDomainUser.slice(indexOfSlash);
        alert("Domain: "  + spsDomain + " User: " + spsUser + " Email: " + spsEmail);
    }
});
}

</script>

Check the following link to see if your data is XML or JSON:

https://<Your_Sharepoint_Domain>/_api/web/currentuser

In the accepted answer Kate uses this method:

var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
0

you can use below function if you know the id of the user:

function getUser(id){
var returnValue;
jQuery.ajax({
 url: "http://YourSite/_api/Web/GetUserById(" + id + ")",
 type: "GET",
 headers: { "Accept": "application/json;odata=verbose" },
 success: function(data) {
       var dataResults = data.d;
       alert(dataResults.Title);
  }
});
}

or you can try

var listURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser";
Amay Kulkarni
  • 828
  • 13
  • 16
0

try this code..

function GetCurrentUsers() {

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

       var currentUsers = currentUser.get_title();
       document.getElementById("txtIssued").innerHTML = currentUsers;

    }

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

}

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
Tokhin
  • 1
  • 2
0

You can use sp page context info:

_spPageContextOnfo.userLoginName

0

This code works with onedrive and sharepoint:

document.querySelector("div.mectrl_accountDetails div#mectrl_currentAccount_secondary").innerHTML

It's the only code i know of that gives you all the info on nearly every site in microsoft's ecosystem. The mectrl_accountDetails element also contains the userid, site id, and other info.

Erik Aronesty
  • 11,620
  • 5
  • 64
  • 44