Welcome to this tutorial! Here, you'll learn how to retrieve various user details in SharePoint Online using the _spPageContextInfo
variable. This is useful for SharePoint admins and web developers who want to display user information on their SharePoint pages.
Reminder: Ensure that the "Enable classic _spPageContextInfo" setting is enabled in the Modern Script Editor web part to access the _spPageContextInfo
object.
_spPageContextInfo
The _spPageContextInfo
is an object provided by SharePoint that contains various properties about the current page context, including user details. These properties can be accessed directly or by assigning them to variables. Below are examples of how to retrieve different user details using this object.
To get the user's display name, which is a string, use the following JavaScript code:
var userDisplayName = _spPageContextInfo.userDisplayName;
console.log("User Display Name: " + userDisplayName);
To get the user's email address, which is a string, use the following JavaScript code:
var userEmail = _spPageContextInfo.userEmail;
console.log("User Email: " + userEmail);
To get the user's login name, which is a string, use the following JavaScript code:
var userLoginName = _spPageContextInfo.userLoginName;
console.log("User Login Name: " + userLoginName);
To get the user's ID, which is a number, use the following JavaScript code:
var userId = _spPageContextInfo.userId;
console.log("User ID: " + userId);
To get the user's principal name, which is a string, use the following JavaScript code:
var userPrincipalName = _spPageContextInfo.userPrincipalName;
console.log("User Principal Name: " + userPrincipalName);
To get the user's title, which is a string, use the following JavaScript code:
var userTitle = _spPageContextInfo.userTitle;
console.log("User Title: " + userTitle);
To get the user's department, which is a string, use the following JavaScript code:
var userDepartment = _spPageContextInfo.userDepartment;
console.log("User Department: " + userDepartment);
To get the user's picture URL, which is a string representing the URL of the user's profile picture, use the following JavaScript code:
var userPictureUrl = _spPageContextInfo.userPictureUrl;
console.log("User Picture URL: " + userPictureUrl);
If you have other questions about the _spPageContextInfo
object and its attributes, please refer to this detailed article for more information.