SharePoint get current user id, name, email, display name programmatically

In this SharePoint tutorial, we will discuss how to get current user id in sharepoint using javascript. Also, we will see how to get current user id, name, email, display it programmatically in SharePoint using JavaScript, Rest API, and CSOM.

  • How to get current user id in sharepoint using javascript
  • Get current user id in sharepoint online using javascript
  • how to get current user id in sharepoint 2013 using javascript
  • sharepoint get current user email
  • sharepoint get current user name
  • sharepoint get current user display name
  • get current user id sharepoint rest API
  • sharepoint get current user display name using rest api
  • How to get logged-in user count in SharePoint programmatically
  • How to get SharePoint Online user profile properties using Rest API, etc.
  • How to get logged in user details in SharePoint
  • Different ways to retrieve logged in user details in SharePoint
  • How to get user profile properties in SharePoint programmatically using CSOM

Here, I am explaining how to show current user details using the JavaScript Object Model (JSOM) and jQuery in SharePoint online.

Below is the code to retrieve current user details like display name, user name, email id, and user id using Jsom and jQuery in SharePoint.

Open your SharePoint site and go to the web part page and then Edit the web part page -> Add Web parts. And then add a script editor web part into the SharePoint web part page.

Get current user id in SharePoint using javascript

Below is the jsom code, to get current user id in sharepoint using javascript. The below code also displays the SharePoint current user name, email and display name.

<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></br>  
    <span id="userId"></span></br>  
    <span id="userTitle"></span></br>  
    <span id="userEmail"></span></br>  
</div>  

Get logged in user count in SharePoint programmatically

Let us see, how to get logged in user count in SharePoint programmatically. Here, we will use the SharePoint server object model code.

Now, we will see how to track the logged-in user count in the SharePoint site using the SharePoint server object model code.

Step 1: Create a list in SharePoint as “Tracking List” which will keep user information like UserName and one more column called Created.

Step 2: If you have enabled FBA in your application, then after successful login, apply the below code to insert the userName in the tracking list.

 SPSecurity.RunWithElevatedPrivileges(delegate ()
                {
                    using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (SPWeb spWeb = spSite.OpenWeb())
                        {
                            SPList spList = spWeb.Lists[Tracking List];
                            spList.ParentWeb.AllowUnsafeUpdates = true;
                            SPListItem item = spList.Items.Add();
                            item["userName "] = Email.tostring();
                            item.Update();
                            spList.ParentWeb.AllowUnsafeUpdates = false;
                        }
                    }
                });

Step 3: Next create a method to filter the count from the tracking list using the SharePoint server object model.

public static VisitorLog GetMaxsiteVisitor()
        {
            try
            {
                VisitorLog VisitorLogs = new VisitorLogs ();
                SPSecurity.RunWithElevatedPrivileges(delegate ()
                {
                    using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (SPWeb web = spSite.OpenWeb())
                        {
                            
                            DateTime curntDt = DateTime.Now;

                            SPList spList = web.Lists[Tracking List];
                            SPQuery querygetTodayCount = new SPQuery();                           

                            string CurrentDate = curntDt.ToString("yyyy-MM-ddTHH:mm:ssZ");                    

                            querygetTodayCount.ViewXml = @"<View><Query><Where><Geq><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>" + CurrentDate + "</Value></Geq></Where></Query></View>";

                            SPListItemCollection itemsTodayCount = spList.GetItems(querygetTodayCount);
                            VisitorLogs.UserCountToday = 0;
                          

                            if (itemsTodayCount != null && itemsTodayCount.Count > 0)
                            {

                                VisitorLogs.UserCountToday = itemsTodayCount.Count;
                            }
                           
                        }
                    }

                });
                return VisitorLogs;
            }

            catch (Exception ex)
            {
                CommonHelper.ProcessDataException(ex);
                return null;
            }
        }

In the above code, I filter the created column to get the count on how many users are login to the application.

This is the one type of easiest way to track how many users are logged in to the site today.

Get logged in user count in SharePoint programmatically
Get logged in user count in SharePoint programmatically

This is how we can get the logged in user count in SharePoint.

How to get current user id in SharePoint 2013 using rest api

The below two examples written by Author Sagar.

Let us see how to get current user display name in SharePoint using Rest API.

The code we can use to know, how to get current logged in user details like display name, email, etc using Rest API in SharePoint 2013/2016/2019 or SharePoint Online.

In SharePoint REST API is quite simple and straightforward, use User ID to get user Title, Email for SharePoint 2013, and apps for SharePoint. use /_api/web/getuserbyid(ID) to get the user field in the response data, we have an “AuthorId” that will get us the user Title, Email, etc.

get current user id sharepoint rest api
get current user id sharepoint rest api

SharePoint get current user display name using Rest API

Step-1: Navigate to your SharePoint 2013 site and create a Wiki Page or a Web Parts page.

Step-2: The process to add your JavaScript code is quite straightforward:
Edit the page, go to the “Insert” tab in the Ribbon and click the “Web Part” option. In the “Web Parts” picker area, go to the “Media and Content” category, select the “Script Editor” Web Part and press the “Add button”.

Step-3: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link click. You can insert the HTML and/or JavaScript code into the dialog.

get current user id sharepoint rest api
get current user id sharepoint rest api
<script src=”/Style Library/scripts/jquery-1.10.1.min.js”></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 Logg = data.d;
//get login name
var loginName = Logg.LoginName.split(‘|’)[1];
alert(loginName);
//get display name
alert(Logg.Title);
}
function onError(error) {
alert(“error”);
}
</script>

In the code above, we’ll get the author id from the list. By passing the author id in to GetUserBuId() method, it will return the user in raw format like “I:O#.f|xxxx|[email protected]”. We can get the login name by splitting the output.

get current user details using rest api in SharePoint online
get current user details using rest api in SharePoint online

Get logged in user id SharePoint javascript

Let us see, how to get current user details using SharePoint 2013 CSOM using JavaScript Object Model (jsom).

In SharePoint 2013 environment, SP.UserProfiles javascript is used to get user profiles and user properties in custom solutions for SharePoint 2013 and apps for SharePoint.

There are various object supported in SP.userProfile namespace. They are given as below.

  • HashTag
  • HashTagCollection
  • PeopleManager
  • PersonProperties
  • ProfileLoader
  • UserProfile
  • UserProfilePropertiesForUser

In this article, I will show the sample code to get the current logged in user using user profile JavaScript.

<script src="/_layouts/15/SP.Runtime.js"></script>
<script src="/_layouts/15/SP.js"></script>
<script src="/_layouts/15/SP.UserProfiles.js"></script>

(function($){

$(document).ready(function(){
// Ensure that the SP.UserProfiles.js file is loaded.
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, ‘SP.UserProfiles.js’);
});

var userProfileProperties;

function loadUserData(){

//Get Current Context
var clientContext = new SP.ClientContext.get_current();

// People Manager Instance
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);

// current user
userProfileProperties = peopleManager.getMyProperties()

clientContext.load(userProfileProperties);

//Execute the Query.
clientContext.executeQueryAsync(onSuccess, onFail);

}

function onSuccess() {
alert(userProfileProperties.get_displayName());
}

function onFail(sender, args) {
alert(“Error Occured: " + args.get_message());
}
})(jQuery);

This is how to get current logged in user details like display name, email, etc using Rest API in SharePoint 2013/2016/2019 or SharePoint Online.

Get SharePoint Online user profile properties using Rest API

This SharePoint Rest API tutorial explains, how to get logged in user profile properties using Rest API in SharePoint Online or SharePoint 2013/2016.

User profile properties provide information about SharePoint users, such as display name, email, account name, and other business and personal information’s including custom properties. Here in this SharePoint 2013 tutorial, we will explain how to retrieve user profile properties using Rest API in SharePoint 2013.

Get login user profile properties using Rest API in SharePoint

Get all properties of the current user by using the below Rest End Point.

http://<siteUri>/_api/SP.UserProfiles.PeopleManager/GetMyProperties

Suppose I want to retrieve a custom field from the user profile property with REST in SharePoint 2013.

The property is searchable in the search box. Name of the custom properties “Employee ID and Division”

But when I try to use http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties, it does not retrieve the custom properties, on the contrary, I can see only the built-in properties like:

  • AccountName
  • DisplayName etc.

I get a node that says UserProfileProperties where there is a Key? But how do I use this?

Let’s proceed

I’ve created an UserProfile with some custom properties.

When I use http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties, I get a result set with all UserProfile properties, including my custom properties. Right now I am using a workaround which iterates through the (big) result set with all properties to get my custom property.

Navigate to your SharePoint 2013 site.

From this page select the Site Actions | Edit Page.

Edit the page, go to the “Insert” tab in the Ribbon and click the “Web Part” option. In the “Web Parts”dialogue, go to the “Media and Content” category, select the Script Editor Web Part and click the “Add button”. Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert the HTML and/or JavaScript as in the following:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
<script type='text/javascript'>
var workEmail = "";
var EmployeeID = "";
var Division = "";
var userDisplayName = "";
var AccountName = "";
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",
headers: { Accept: "application/json;odata=verbose" },
success: function (data) {
try {
//Get properties from user profile Json response
userDisplayName = data.d.DisplayName;
AccountName = data.d.AccountName;
var properties = data.d.UserProfileProperties.results;
for (var i = 0; i < properties.length; i++) {
if (property.Key == "WorkEmail") {
workEmail = property.Value;
}
if (property.Key == "EmployeeID") {
EmployeeID = property.Value;
}
if (property.Key == "Division") {
Division = property.Value;
}
}

$('#AccountName').text(AccountName);
$('#userDisplayName').text(userDisplayName);
$('#EmployeeID').text(EmployeeID);
$('#workEmail').text(workEmail);
$('#Division').text(Division);
} catch (err2) {
//alert(JSON.stringify(err2));
}
},

error: function (jQxhr, errorCode, errorThrown) {
alert(errorThrown);
}
});
</script>

<h2><strong>Employee Details</strong></h2>
<br />
AccountName <span id="AccountName"></span>
DisplayName <span id="userDisplayName"></span>
EmployeeID <span id="EmployeeID"></span>
Email Address <span id="workEmail"></span>
Division <span id="Division"></span>

Finally, the result looks as in the following snapshot:

get user profile properties sharepoint online rest api
get user profile properties sharepoint online rest api

List of User Properties (Use the GetPropertiesFor function for these):

  • AccountName
  • DirectReports
  • DisplayName
  • Email
  • ExtendedManagers
  • ExtendedReports
  • IsFollowed
  • LatestPost
  • Peers
  • PersonalUrl
  • PictureUrl”
  • Title
  • UserProfileProperties
  • UserUrlList of User Profile Properties :
  • AboutMe
  • SPS-LastKeywordAdded
  • AccountName
  • SPS-Locale
  • ADGuid
  • SPS-Location
  • Assistant
  • SPS-MasterAccountName
  • CellPhone
  • SPS-MemberOf
  • Department
  • SPS-MUILanguages
  • EduExternalSyncState
  • SPS-MySiteUpgrade
  • EduOAuthTokenProviders
  • SPS-O15FirstRunExperience
  • EduPersonalSiteState
  • SPS-ObjectExists
  • EduUserRole
  • SPS-OWAUrl
  • Fax
  • SPS-PastProjects
  • FirstName
  • SPS-Peers
  • HomePhone
  • SPS-PersonalSiteCapabilities
  • LastName
  • SPS-PersonalSiteInstantiationState
  • Manager
  • SPS-PhoneticDisplayName
  • Office
  • SPS-PhoneticFirstName
  • PersonalSpace
  • SPS-PhoneticLastName
  • PictureURL
  • SPS-PrivacyActivity
  • PreferredName
  • SPS-PrivacyPeople
  • PublicSiteRedirect
  • SPS-ProxyAddresses
  • QuickLinks
  • SPS-RegionalSettings-FollowWeb
  • SID
  • SPS-RegionalSettings-Initialized
  • SISUserId
  • SPS-ResourceAccountName
  • SPS-AdjustHijriDays
  • SPS-ResourceSID
  • SPS-AltCalendarType
  • SPS-Responsibility
  • SPS-Birthday
  • SPS-SavedAccountName
  • SPS-CalendarType
  • SPS-SavedSID
  • SPS-ClaimID
  • SPS-School
  • SPS-ClaimProviderID
  • SPS-ShowWeeks
  • SPS-ClaimProviderType
  • SPS-SipAddress
  • SPS-ContentLanguages
  • SPS-Skills
  • SPS-DataSource
  • SPS-SourceObjectDN
  • SPS-Department
  • SPS-StatusNotes
  • SPS-DisplayOrder
  • SPS-Time24
  • SPS-DistinguishedName
  • SPS-TimeZone
  • SPS-DontSuggestList
  • SPS-UserPrincipalName
  • SPS-Dotted-line
  • SPS-WorkDayEndHour
  • SPS-EmailOptin
  • SPS-WorkDayStartHour
  • SPS-FeedIdentifier
  • SPS-WorkDays
  • SPS-FirstDayOfWeek
  • Title
  • SPS-FirstWeekOfYear
  • UserName
  • SPS-HashTags
  • UserProfile_GUID
  • SPS-HireDate
  • WebSite
  • SPS-Interests
  • WorkEmail
  • SPS-JobTitle
  • WorkPhone
  • SPS-LastColleagueAdded

This is how to get current user profile properties using Rest API in SharePoint 2013/2016/2019 or SharePoint Online.

How to get logged in user details in SharePoint (Various ways)

Let us see, how to get current logged in user details in SharePoint? There are various ways to get logged in user details in SharePoint 2019/2016/2013 or SharePoint Online.

This part of the article is written by our author Akash Kumhar.

Get logged in user details using SharePoint Server object model (SSOM)

We can easily retrieve logged in user details using the SharePoint Server object model (SSOM). Remember the below code you have to run in the SharePoint server because it requires Micorosft.SharePoint.dll

Code:

SPSite site = new SPSite("http://Site URL");
SPWeb web = site.OpenWeb();
SPUser user = web.CurrentUser;
Console.Write("SSOM\nUser Information\nUser ID : " + user.ID + "\nUser Login Name : " + user.LoginName + "\nUser Title: " + user.Name);
Console.ReadLine();
get logged in user details in SharePoint
get logged in user details in SharePoint

Get logged in user details using Client Side Object Model (CSOM)

Similarly, we can retrieve logged in user details by using the Client-Side Object Model (CSOM). To run client-side code we need the below two dlls:

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll

Code:

using (ClientContext context = new ClientContext("http://Site URL"))
{
NetworkCredential myNetCred = new NetworkCredential("akashkumhar", "[email protected]");
context.Credentials = myNetCred;
Web web = context.Web;
context.Load(web);
User user = context.Web.CurrentUser;
context.Load(user);
context.ExecuteQuery();
Console.Write("CSOM\nUser Information\nUser ID : " + user.Id + "\nUser Login Name : " + user.LoginName + "\nUser Title: " + user.Title);
Console.ReadLine();
}

Output:

sharepoint get current user
sharepoint get current user

Get logged in user details using REST API

First, we will see how to check the server response on the REST API request by hitting a Simple EndPoint URL on the browser.

This EndPoint URL provides all the information about the current logged in user. The URL is constructed with the use of CurrentUser as the EndPoint, which returns the User ID, Login Name, Title, etc.

EndPoint URL:

<Your Site>_api/web/CurrentUser

Example: http://win-eqalhem27jl:7575/sites/one/_api/Web/CurrentUser

Output:

get current user id sharepoint rest api
get current user id sharepoint rest api

We can also get the information about the current logged in user by fetching the current logged in user details from the User Information List.

For this approach, we need the ID of the current logged in user.

The EndPoint URL for this can be constructed with SiteUserInfoList/items(Curent User ID) as the EndPoint.
EndPoint URL:

<your site>_api/web/SiteUserInfoList/items(<your user ID>)?

Example: http://win-eqalhem27jl:7575/sites/one/_api/Web/SiteUserInfoList/Items(8)?$select=ID,Name,Title

Output:

how to get current user id in sharepoint 2013 using rest api
how to get current user id in sharepoint 2013 using rest api

Practical Usage of the EndPoint URLs:

Code:

<script src="https://win-eqalhem27jl:7575/sites/one/SiteAssets/1.11.2.jquery.js"></script>
<script type="text/javascript">
$(function () {
fetchUserInfo();
});

function fetchUserInfo()
{
$.ajax
({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/SiteUserInfoList/Items(8)?$select=ID,Name,Title",
method: "GET",
headers:
{
"Accept": "application/json;odata=verbose",
},
cache: false,
async: false,
success: function(data)
{
var userID = data.d.ID;
var userLoginName = data.d.Name;
var userName = data.d.Title;
alert("User Details: ID > " + userID + ", Name > " + userName + ", LoginName > " + userLoginName)
},
error: function(data)
{
alert(data.responseJSON.error);
}
});
}
</script>

Output:

Retrieve logged in user details using REST API
get current user id sharepoint rest api

Get logged in user details using JavaScript Object Model (JSOM)

By using the JavaScript object model we will be able to retrieve current logged in user’s details.

Code:

<script src="https://win-eqalhem27jl:7575/sites/one/SiteAssets/1.11.2.jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var currentUser;
if (SP.ClientContext != null) {
SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.js');
}
else {
SP.SOD.executeFunc('sp.js', null, getCurrentUser);
}
});

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

function onSuccessMethod(sender, args) {
var userID = currentUser.get_id();
var userLoginName = currentUser.get_loginName();
var userName = currentUser.get_title();
currentUserAccount = userLoginName.substring(userLoginName.indexOf("|") + 1);
}

function onRequestFail(sender, args) {
alert('request failed' + args.get_message());
}

</script>

Output:

get logged in user id sharepoint javascript
get logged in user id sharepoint javascript

Get logged in user details using PowerShell

We can retrieve current logged-in user details using PowerShell in SharePoint 2013. We can run the below PowerShell script using Windows PowerShell ISE or by using visual studio code.

Code:

Add-PSSnapin Microsoft.Sharepoint.Powershell
$site=Get-SPSite "http://win-eqalhem27jl:7575/sites/one/"
$web=$site.RootWeb
$strLoginName=$web.CurrentUser.LoginName
$strID=$web.CurrentUser.ID
$strName=$web.CurrentUser.Name
Write-Host " Current User Id : " $strID -ForegroundColor green;
Write-Host " Current User Login Name : " $strLoginName -ForegroundColor green;
Write-Host " Current User Name : " $strName -ForegroundColor green

Output:

sharepoint get current user id powershell
sharepoint get current user id powershell

This is how to get SharePoint current or logged in user details using Rest API, CSOM, SSOM, PowerShell, etc.

Get user profile properties in SharePoint programmatically using CSOM

Let us see, how to get user profile properties in sharepoint programmatically using CSOM (C#).

If you want to retrieve user profile properties, then you must configure SharePoint user profile service for your SharePoint environment or sites.

To work with CSOM in SharePoint, you can create a .Net application like an asp.net web application, windows application, or web application. Here, I have created an asp.net application to implement this.

Open the Asp.net solution, and then go to the reference and add the below dlls.

  • Microsoft.SharePoint.Client
  • Microsoft.SharePoint.Client.Runtime
  • Microsoft.SharePoint.Client.UserProfiles

You can get these dlls from NuGet or even you can download and install SharePoint Online Client Components SDK in your system and refer to the dlls from there.

In this step, we have to provide the SharePoint site URL, user Name, Domain user Name, Domain Password, and domain name.

Get user profile properties in SharePoint programmatically using CSOM
Get user profile properties in SharePoint programmatically using CSOM

Get user profile properties SharePoint 2013

Now, we will see how to get use profile properties in SharePoint 2013 programmatically using C#.Net (csom).

clientContext.ExecutingWebRequest += clientContext_ExecutingWebRequest;
                clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
                clientContext.Credentials = new NetworkCredential(domainUserId, DomainPassword, DomailName);  //new SharePointOnlineCredentials(targetUser, passWord);

                // Get the people manager instance for tenant context
                PeopleManager peopleManager = new PeopleManager(clientContext);
                PersonProperties personProperties = peopleManager.GetPropertiesFor(userName);
                clientContext.Load(personProperties);
                clientContext.ExecuteQuery();
                DataTable dtUserDetails = new DataTable();
                dtUserDetails.Columns.Add("User ID", typeof(string));
                dtUserDetails.Columns.Add("Name", typeof(string));
                dtUserDetails.Columns.Add("Email", typeof(string));
                dtUserDetails.Columns.Add("Designation", typeof(string));
                dtUserDetails.Columns.Add("Manager", typeof(string));
                DataRow dtusers = dtUserDetails.NewRow();
                dtusers["User ID"] = personProperties.AccountName;
                dtusers["Name"] = personProperties.DisplayName;
                dtusers["Email"] = personProperties.Email;
                dtusers["Designation"] = personProperties.Title;
                dtusers["Manager"] =                personProperties.UserProfileProperties["Manager"].ToString();
                dtUserDetails.Rows.Add(dtusers);

Get Employee hierarchy in SharePoint using CSOM

Now, we will see how to get employee hierarchy in SharePoint using CSOM.

using (ClientContext clientContext = new ClientContext(serverUrl))
            {
                clientContext.ExecutingWebRequest += clientContext_ExecutingWebRequest;
                clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
                clientContext.Credentials = new NetworkCredential(domainUserId, DomainPassword, DomailName);  //new SharePointOnlineCredentials(targetUser, passWord);
                PeopleManager peopleManager = new PeopleManager(clientContext);
                PersonProperties personProperties = peopleManager.GetPropertiesFor(userName);
                clientContext.Load(personProperties);
                clientContext.ExecuteQuery();
                List<string> managers = new List<string>();
                string contextManagerName = personProperties.UserProfileProperties["Manager"].ToString();
                managers.Add(contextManagerName);
                for (int i = 0; i < 100; i++)
                {
                    PersonProperties contextperson = peopleManager.GetPropertiesFor(contextManagerName);
                    clientContext.Load(contextperson);
                    clientContext.ExecuteQuery();
                    contextManagerName = contextperson.UserProfileProperties["Manager"] ?? string.Empty;

                    if (string.IsNullOrEmpty(contextManagerName) ||
                        contextperson.UserProfileProperties["Title"].Equals
                        ("President", StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }
                    else
                    {
                        managers.Add(contextManagerName);
                    }

                    i++;
                }

You may like following SharePoint tutorials:

Once you execute the jsom code, it will display the current logged in user display name, email, user id and user login name in SharePoint.

I hope this tutorial helps use to learn:

  • get current user id in sharepoint using javascript
  • get current user id in sharepoint online using javascript
  • how to get current user id in sharepoint 2013 using javascript
  • how to get current user name in sharepoint 2013 using javascript
  • how to get current user login name in sharepoint using javascript
  • how to get current user name in sharepoint 2013 using javascript
  • sharepoint get current user display name using rest api
  • How to get SharePoint Online user profile properties using Rest API
  • How to get current logged in user details in SharePoint
  • Different ways to retrieve logged in user details in SharePoint
  • Get user profile properties in SharePoint programmatically using CSOM
  • >