Check Current User Is Belongs To A Group In SharePoint 2013 Using JSOM

In this blog, I would like to check with JavaScript, if the current logged in user is in a specified and specific group or not. Refer to jQquery Library in your script, not SP Services and use ExecuteOrDelayUntilScriptLoaded in function called and not the function definiton. Refer the code given below.
  1. Open your Visual Studio
  2. Access SharePoint hosted app in your Visual Studio.
  3. Copy the code given below and paste the code given below in your app.
  4. Change the group name and run it.
Call the code given below in your document.ready or page load function.
  1. CurrentUserMemberOfGroup("SPGowtham"function (isCurrentUserInGroup) {  
  2.   if(isCurrentUserInGroup)  
  3.   {  
  4.      console.log('user is member of the group');   
  5.   }  
  6. lse  
  7. {  
  8. console.log('user is not member of the group');  
  9. }  
  10.   
  11. });  
Use this common function and use it to check whether the user is a member of this group or not.
  1. function CurrentUserMemberOfGroup(groupName, OnComplete) {  
  2.    
  3.         var ctx = new SP.ClientContext.get_current();  
  4.         var currentUser = ctx.get_web().get_currentUser();  
  5.         ctx.load(currentUser);   
  6.         var Groups = currentWeb.get_siteGroups();  
  7.         ctx.load(Groups);   
  8.         var group = Groups.getByName(groupName);  
  9.         ctx.load(group);          
  10.         var groupUsers = group.get_users();  
  11.         ctx.load(groupUsers);  
  12.    
  13.         ctx.executeQueryAsync(  
  14.                 function(sender, args) {  
  15.                    var userInGroup = UserInGroup(currentUser,group);           
  16.                    OnComplete(userInGroup);  
  17.                 },  
  18.                 function OnFailure(sender, args) {  
  19.                    OnComplete(false);  
  20.                 }  
  21.         );  
  22.           
  23.         function UserInGroup(user,group)  
  24.         {  
  25.             var groupUsers = group.get_users();  
  26.             var userInGroup = false;  
  27.             var groupUserEnumerator = groupUsers.getEnumerator();  
  28.             while (groupUserEnumerator.moveNext()) {  
  29.                 var groupUser = groupUserEnumerator.get_current();  
  30.                 if (groupUser.get_id() == user.get_id()) {  
  31.                     userInGroup = true;  
  32.                     break;  
  33.                 }  
  34.             }  
  35.             return userInGroup;  
  36.         }  
  37. }  
Thanks for reading my blog. 
Ebook Download
View all
Learn
View all