4

I am using SharePoint 2013 Online and I'm looking for some JavaScript and html to display the current logged in user on the site like for example:

Hello (Username)

If anyone could help or just point myself in the correct direction it will be a help

6

I'm using this:

<script type="text/javascript">

var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();

function GetCurrentUser() {
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("Hello " + loginName);

    // to set the "hello username" into the page
    document.getElementById("id").innerHTML = "Hello " + loginName;
    }

function onError(error) {
  alert(error);
  }

</script>

The alertbox will show you something like: "Hello Firstname Lastname"

Also you can use data.d.LoginName.split('|')[1] instead of data.d.Title and modify the output a little bit.

If you want to print the "Hello Username" directly to the page you can use:

document.getElementById("id").innerHTML = "Hello " + loginName;
| improve this answer | |
  • Hi Patrick thanks for this however i'm trying to add this to the page, not as a alert, but more to display as Text – 011011010101110100001010010 Jun 18 '15 at 10:45
  • I'm doing exactly the same to "Welcome the logged in user". Therefore you only have to set a id for your div where it should be shown and then put the id (e.g. id="welcome") into the code. document.getElementById("welcome").innerHTML = "Hello " + loginName; Also updated the script. – Patrick Jun 18 '15 at 10:52
  • 1
    Note: Guessing you use jQuery in your example (based on $.ajax). You can use CurrentUser as end point. You can use $.getJSON because OP is on SharePoint Online (no need for odata type). You can use jQuery to select and set value on element. E.g., $.getJSON("/_api/Web/CurrentUser").done(function(user) { $('#id').text(user.data.d.Title); }); – eirikb Jun 18 '15 at 11:09
3

JavaScript Object Model can be very easily used to get the current user.

// Getting current user detail
function getCurrentUser() {
    try {
        var clientContext = new SP.ClientContext.get_current();
        var tempcurrentUser = clientContext.get_web().get_currentUser();
        clientContext.load(tempcurrentUser); 
        clientContext.executeQueryAsync(function () {
            var index = tempcurrentUser.get_loginName().indexOf('|') + 1;
            var currentUser = tempcurrentUser.get_loginName().substring(index);
            alert('Hello ' + currentUser); // Here you will get name of the user

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

function queryFailure () {
    alert('error');
}

//You can call the function like this
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getCurrentUser);
| improve this answer | |
  • Is it possible to get the display name and login id by passing the parameter EmailID – userAZLogicApps Feb 21 '18 at 17:01
1

Code given in the below link demonstrates how to get the current user name by using simple CSOM,

http://www.enjoysharepoint.com/Articles/Details/get-current-logged-in-username-in-sharepoint-2013-using-javascript-20982.aspx

| improve this answer | |
1

Just replace the element '#name' for whatever your "hello, userName" is.

    function getCurrentUser() 
    {  
        console.log('Made it');
        var ctx = SP.ClientContext.get_current();
        var web = ctx.get_web();
        var currentUserObj = web.get_currentUser();
        ctx.load(currentUserObj);
        ctx.executeQueryAsync(
            function() 
            {
                var displayName = currentUserObj.get_title();           
                $('#name').val(displayName);
            }, 
                function(sender, args) 
                {
                     console.log("An error occured: " + args.get_message());
                }); //end get currentUser display
    }
| improve this answer | |
1

Best and simple way to get current logged in user name is _spPageContextInfo.

_spPageContextInfo :

_spPageContextInfo is a global variable usually available on any SharePoint page. This variable stores basic information about current web and current user.

Below are the Some examples:

1. To Get User Display Name:

<script type="text/javascript"> var currentUserName=_spPageContextInfo.userDisplayName; </script>

Eg: "Vishal"

2. To Get User Login Name:

<script type="text/javascript"> var currentUserLoginName=_spPageContextInfo.userLoginName; </script>

Eg: "Vishal@mycompany.onmicrosoft.com"

3. To Get User Id:

<script type="text/javascript"> var userID=_spPageContextInfo.userId; </script>

Eg:10

4. To Get Web Title:

<script type="text/javascript"> var currentWebTitle=_spPageContextInfo.webTitle; </script>

Eg: "My Team Site"

To view all properties :

Right click on page --> click on "View Page Source" --> Find "_spPageContextInfo"

| improve this answer | |
  • _spPageContextInfo.userDisplayName is undefined – Ofer Gal Jul 12 '18 at 19:52
  • Note: _spPageContextInfo.userId actually only gives a number, not the domain\username like one might think. – vapcguy Mar 16 '19 at 6:17
0

Another possibility that doesn't require javascript and will play nicely in scenarios where you cannot deploy custom server side code (locked down on-prem environments, SP Hosted apps/add-ins, or SharePoint Online (Office 365)...

If you have ability to modify (master) page (i.e. with SharePoint Designer), you might consider placing an ASP.NET LoginControl on the page. This wouldn't require javascript at all (note that it displays the RAW username, not the friendly display name):

<asp:LoginName runat="server" id="loginName" FormatString="Hello, {0}"></asp:LoginName>
| improve this answer | |
0
alert("Hello " + _spPageContextInfo.userLoginName);

You can use it as per your scenario.

| improve this answer | |

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.