A few days ago, I was working on JSOM (JavaScript object model) on SharePoint Online. As per the business requirement, I had to check if he/she is a member of a particular SP Group or not. In that scenario, I used the following code.
Steps to use the code
To use the code, this function can be added to the targeted code file or to use in a SharePoint custom list forms or in a page. Adding to the Script Editor web part or Content Editor web part will be a good choice.
The following function named "IsGroupMember" is the function which returns a boolean value with True/False. And this function gets three parameters - the name of the Group, the user from whom we want to check, and the ClientContext. Also, it is important to mention that with groupName variable, a string value as the group visual name needs to be sent and with cUser variable, SPUser's user name needs to be sent.
Code Snippet
- function IsGroupMember(groupName, cUser, clientContext) {
- var deferred = $.Deferred();
- var currentWeb = clientContext.get_web();
-
- var allGroups = currentWeb.get_siteGroups();
- clientContext.load(allGroups);
-
- var group = allGroups.getByName(groupName);
- clientContext.load(group);
-
- var groupUsers = group.get_users();
- clientContext.load(groupUsers);
-
- clientContext.executeQueryAsync(
- function onQuerySucceeded(sender, args) {
- var isUserInGroup = false;
- var groupUserEnumerator = groupUsers.getEnumerator();
- while (groupUserEnumerator.moveNext()) {
- var groupUser = groupUserEnumerator.get_current();
- if (groupUser.get_id() == cUser.get_id()) {
- isUserInGroup = true;
- break;
- }
- }
- deferred.resolve(isUserInGroup);
- },
- function onQueryFailed(sender, args) {
- console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
- deferred.resolve(false);
-
- }
- );
- return deferred.promise();
- }
Notes
In this code snippet, deferred - promise is used to increase the usability. This can be ignored if the developer wants to simply return the value or can use onComplete function.