How to Verify if current user is a member of Sharepoint Group via JavaScript
Introduction:
In this article we will explore , How to verify the current user is a member of the Sharepoint group.
Based on the access Showing and hiding div elements.
Solution:
1. Add the below javascript code and save as verify.js file.
Formula:
function IsCurrentUserMemberOfGroup(groupName, OnComplete) {
var currentContext = new SP.ClientContext.get_current(); var currentWeb = currentContext.get_web(); var currentUser = currentContext.get_web().get_currentUser(); currentContext.load(currentUser); var allGroups = currentWeb.get_siteGroups(); currentContext.load(allGroups); var group = allGroups.getByName(groupName); currentContext.load(group); var groupUsers = group.get_users(); currentContext.load(groupUsers); currentContext.executeQueryAsync(OnSuccess,OnFailure); function OnSuccess(sender, args) { var userInGroup = false; var groupUserEnumerator = groupUsers.getEnumerator(); while (groupUserEnumerator.moveNext()) { var groupUser = groupUserEnumerator.get_current(); if (groupUser.get_id() == currentUser.get_id()) { userInGroup = true; break; } } OnComplete(userInGroup); } function OnFailure(sender, args) { OnComplete(false); } } function IsCurrentUserWithContributePerms() { IsCurrentUserMemberOfGroup("CustomMembers", function (isCurrentUserInGroup) { if(isCurrentUserInGroup) { // The current user is in the [CustomMembers] group $('#div1').show(); $('#div2').show(); } else { $('#div1').hide(); $('#div2').hide(); } }); } ExecuteOrDelayUntilScriptLoaded(IsCurrentUserWithContributePerms, 'SP.js'); |
2. Add the reference link to the javascript file in the master page.
<script src="/SiteAssets/js/verify.js"></script>
|
Now on every page refresh ,script will verify the current user in the mentioned Sharepoint group and show the div elements.
Hope this article helps !!
Thanks for reading this article ! ! please leave your comments and suggestion about this article.
No comments