Check User Membership In A Security Group In SharePoint Using Javascript Object Model

One of the common requirements while working on the client side development is to check a user’s membership in a particular group and perform some follow up actions based on the group presence (like show/hide fields).

In this blog, we will see how to check if a user is present in SharePoint security group, using JavaScript Object Model. Let’s say, we have a group named ‘Test Group’ and we want to check the user’s presence in this group.


We need to use JSOM code, given below, to test the user’s presence in ‘Test Group’.

  1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
  2.   
  3.     <script language="javascript" type="text/javascript">  
  4.   
  5.     $(document).ready(function() {  
  6.         SP.SOD.executeFunc('sp.js''SP.ClientContext', checkUserMembership);  
  7.     });  
  8.   
  9. var oGroupColl;  
  10. function checkUserMembership() {  
  11.   
  12. //Get the client context, web and current user object  
  13.     var clientContext = new SP.ClientContext.get_current();  
  14.     var oWeb = clientContext.get_web();  
  15.     oCurrentUser = oWeb.get_currentUser();  
  16.   
  17. //Get the group collection  
  18.     oGroupColl = oCurrentUser.get_groups();  
  19.   
  20. //Load the client context and execute the batch  
  21.     clientContext.load(oGroupColl);  
  22.     clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
  23. }  
  24.   
  25. function QuerySuccess() {  
  26.   
  27.   
  28. //Get the group collection and loop through it  
  29.     var groupMembership = false;  
  30.     var groupCollEnumerator = oGroupColl.getEnumerator();  
  31.     while (groupCollEnumerator.moveNext()) {  
  32.         var group = groupCollEnumerator.get_current();  
  33.   
  34.   
  35. //Check if a particular group is present in user's group collection  
  36.         if(group.get_title() == "Test Group") {  
  37.             isMember = true;  
  38.             console.log('User is present in Test Group');  
  39.             break;  
  40.   
  41.         }  
  42.     }  
  43. }  
  44.   
  45. function QueryFailure(sender,args) {  
  46.     console.log('Request failed'+ args.get_message());  
  47. }  
  48.   
  49. </script>   

We can add the code, mentioned above, to Content Editor Web part and see the output in the console, as shown below-


Summary - Thus, we saw how to check the user’s presence in a SharePoint Security group, using JavaScript Object Model.

Ebook Download
View all
Learn
View all