Ram Prasad
 

JavaScript Client Code to get current user's groups for SharePoint Site

Feb, 25 2015
 
1 min/s
 
 

Below is a sample code snippet using JavaScript client object model, which gets the list of SharePoint groups the current user is part of.

<script type="text/javascript">
var clientContext = new SP.ClientContext.get_current();
var oWeb = clientContext.get_web();
var currentUser = oWeb.get_currentUser();
var allGroups = currentUser.get_groups();
clientContext.load(allGroups);

clientContext.executeQueryAsync(OnSuccess, OnFailure);

function OnSuccess(sender, args)
{
	var grpsEnumerator = allGroups.getEnumerator();
	while(grpsEnumerator.moveNext())
	{
		//This object will have the group instance
		//which the current user is part of. 
		//This is can be processed for further 
		//operations or business logic.
		var group = grpsEnumerator.get_current();

		//This gets the title of each group
		//while traversing through the enumerator.			
		var grpTitle = group.get_title();
	}
}

function OnFailure(sender, args)
{
	console.log(args.get_message());
}

</script>