Check Existence of User in SharePoint Group using JSOM

While working with SharePoint objects it’s required to check whether user is present in which SharePoint group.Hence, the below script comes in handy to check existence of user in SharePoint group using JSOM.

ExecuteOrDelayUntilScriptLoaded(IsUserExists, “sp.js”);
var spfGroup;
var spfUsers;
var context;
var spfGroupCollection;
var spfUser;

function IsUserExists() {
context = SP.ClientContext.get_current();
spfGroupCollection = context.get_web().get_siteGroups();
spfUser = context.get_web().get_currentUser();
spfGroup = spfGroupCollection.getById(101);
or
spfGroup = spfGroupCollection.getByName(“SPF Owners”);
context.load(spfGroup);
context.load(spfUser);
context.executeQueryAsync(Function.createDelegate(this, this.OnGetGroupSuccess), Function.createDelegate(this, OnFailure));

}

function OnGetGroupSuccess() {
spfUsers = spfGroup.get_spfUsers();
context.load(spfUsers);
context.executeQueryAsync(Function.createDelegate(this, this.OnGetuserSuccess), Function.createDelegate(this, OnFailure));
}

function OnGetuserSuccess() {
var userEnumerator = spfUsers.getEnumerator();
while (userEnumerator.moveNext()) {
var spfUser = userEnumerator.get_current();
if (spfUser.get_id() == spfUser.get_id()) {
alert(“User Exists”);
break;
} else {

}
}
}

function OnFailure(sender, args) {
alert(“Failed to execute IsCurrentUserMemberOfGroup method”);
}

Hope this blog helps 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s