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.
- Open your Visual Studio
- Access SharePoint hosted app in your Visual Studio.
- Copy the code given below and paste the code given below in your app.
- Change the group name and run it.
Call the code given below in your document.ready or page load function.
- CurrentUserMemberOfGroup("SPGowtham", function (isCurrentUserInGroup) {
- if(isCurrentUserInGroup)
- {
- console.log('user is member of the group');
- }
- lse
- {
- console.log('user is not member of the group');
- }
-
- });
Use this common function and use it to check whether the user is a member of this group or not.
- function CurrentUserMemberOfGroup(groupName, OnComplete) {
-
- var ctx = new SP.ClientContext.get_current();
- var currentUser = ctx.get_web().get_currentUser();
- ctx.load(currentUser);
- var Groups = currentWeb.get_siteGroups();
- ctx.load(Groups);
- var group = Groups.getByName(groupName);
- ctx.load(group);
- var groupUsers = group.get_users();
- ctx.load(groupUsers);
-
- ctx.executeQueryAsync(
- function(sender, args) {
- var userInGroup = UserInGroup(currentUser,group);
- OnComplete(userInGroup);
- },
- function OnFailure(sender, args) {
- OnComplete(false);
- }
- );
-
- function UserInGroup(user,group)
- {
- var groupUsers = group.get_users();
- var userInGroup = false;
- var groupUserEnumerator = groupUsers.getEnumerator();
- while (groupUserEnumerator.moveNext()) {
- var groupUser = groupUserEnumerator.get_current();
- if (groupUser.get_id() == user.get_id()) {
- userInGroup = true;
- break;
- }
- }
- return userInGroup;
- }
- }
Thanks for reading my blog.