Getting Current User With Client Side Javascript In Sharepoint 2013

The Problem: Accessing User Information Client-Side

Client-side code in SharePoint has limited permissions, making accessing user information difficult. Solutions require custom permissions, server-side code, or complex workarounds.

A Simple Solution: The SP.UserProfiles JavaScript Object

SP.UserProfiles provides easy access to basic user information. It allows retrieving current user data like login name, email, etc. SP.UserProfiles works client-side without custom permissions.

Usage Examples

Get current user login name

The getLoginName method of SP.UserProfiles can be used to retrieve the current user’s login name in SharePoint. This returns a string with the user’s domain\\username login identifier. For example:

var loginName; 

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {

  var context = new SP.ClientContext.get_current();
  var userProfile = new SP.UserProfiles.PeopleManager(context).getMyProperties();

  context.load(userProfile); 
  context.executeQueryAsync(function() {
    loginName = userProfile.get_loginName(); 
  }, 
  function(sender, args) {
     console.log('Error getting login name: ' + args.get_message());
  });
});

This asynchronously retrieves the login name string for the current user after the page loads. The profile object also contains other useful information like user email and role properties.

Retrieve user email address

The user profile object provided by SP.UserProfiles contains an email property to easily access the current user’s email address. For example:

var userEmail;

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {  
  var context = new SP.ClientContext.get_current();
  var userProfile = new SP.UserProfiles.PeopleManager(context).getMyProperties();
   
  context.load(userProfile);
  context.executeQueryAsync(function() {
    userEmail = userProfile.get_email();
  }, 
  function(sender, args) {
     console.log('Error getting email: ' + args.get_message());  
  });
});  

By loading the SP.UserProfiles.PersonProperties object into the context and executing the async query, we can access the email property to get the user’s email address string.

Check if user is site administrator

The user profile contains an IsSiteAdmin property that can be used to check if the current user has site collection administrator permissions. For example:

  
var isAdmin;

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {

  var context = new SP.ClientContext.get_current();
  var userProfile = new SP.UserProfiles.PeopleManager(context).getMyProperties();
   
  context.load(userProfile);
  context.executeQueryAsync(function() {
    isAdmin = userProfile.get_isSiteAdmin();
  },
  function(sender, args) {
    console.log('Error checking admin status: ' + args.get_message());
  });
});

By retrieving the IsSiteAdmin boolean property we can check if the current user has administrator access rights on the site. This allows client-side code to conditionally show/hide UI elements for admins.

Additional Tips and Tricks

Caching user profiles for better performance

Retrieving user profile objects via SP.UserProfiles can require multiple server round trips. For better performance these can be cached locally using sessionStorage or cookies to avoid having to requery every page load. For example:

// Check cache  
var profile = sessionStorage.getItem('userProfile');

if (profile) {
  // use cached profile object
}
else {

  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {

    var context = new SP.ClientContext.get_current();
    
    // Get profile and cache  
    var profile = new SP.UserProfiles.PeopleManager(context).getMyProperties();
    sessionStorage.setItem('userProfile', profile);
    
    // Use profile
  }); 
}

By caching the profile locally, we avoid having to retrieve it repeatedly on each page view.

Handling errors gracefully

When using asynchronous SP.UserProfiles queries, it is important to handle any errors gracefully. For example:

SP.SOD.executeFunc('sp.js', function() {

  var context = SP.ClientContext.get_current();
  var userProfile = new SP.UserProfiles.PeopleManager(context).getMyProperties();

  context.executeQueryAsync(function() {
    // user profile succeeded 
  },
  function(sender, args) {
    // An error occurred
    console.log('Error message', args.get_message());
  }); 
});

Having try/catch blocks around the code can also help handle errors appropriately without affecting site functionality.

Extending with additional user profile properties

The SP.UserProfiles.PersonProperties object contains the most commonly used attributes like login name and email. Additional custom properties can be accessed using the ProfileLoader object. For example:

var userLanguage;  

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {

  var context = new SP.ClientContext.get_current();
  var profileLoader = new SP.UserProfiles.ProfileLoader.getUserProfilePropertiesFor(context, ["PreferredLanguage"]);
   
  context.executeQueryAsync(function() {
    userLanguage = profileLoader.get_userProfileProperties()['PreferredLanguage'];
  },
  function(sender, args) {
    console.log('Error getting user language: ' + args.get_message());
  });
}); 

This allows retrieving custom user profile properties defined for the SharePoint environment.

Summary

SP.UserProfiles enables simple access to user data client-side. Key methods provide login, email, and role info. Usage is easy but some best practices around caching, error handling, and custom extensions apply.

Leave a Reply

Your email address will not be published. Required fields are marked *