Get Users from SharePoint Group using JavaScript Client Object Model

In this post we will discuss how we can retrieve users from SharePoint group using JavaScript client object model.

You can check below articles:
How to check user belongs to SharePoint group using JavaScript client object model?

Get all SharePoint groups using JavaScript Object model

SharePoint Online Add Update Delete Item from List using SPServices

Put the below code in a Script editor web part. It will download all the users from the particular group.

<input type=”button” id=”btnUpdate” value=”Export Site Users” onclick=”GenerateReport();” />

<script type=”text/javascript”>
var siteUrl = ‘http://win-pfcp2dgt8di/sites/EnjoySharePoint/’;
var groups=[’20’];
var gp_users=[];
var gp_name;

function GenerateReport()
{
retrieveAllUsersInGroup(’20’);
}

function retrieveAllUsersInGroup(grp) {

var clientContext = new SP.ClientContext(siteUrl);
var collGroup = clientContext.get_web().get_siteGroups();
var oGroup = collGroup.getById(grp);
this.collUser = oGroup.get_users();
clientContext.load(collUser);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
var userInfo = ”;
var userEnumerator = collUser.getEnumerator();
while (userEnumerator.moveNext()) {
var oUser = userEnumerator.get_current();

userInfo += ‘\nUser: ‘ + oUser.get_title() +
‘\nID: ‘ + oUser.get_id() +
‘\nEmail: ‘ + oUser.get_email() +
‘\nLogin Name: ‘ + oUser.get_loginName();
gp_users.push(oUser.get_title());

}
generateexcel();
}

function onQueryFailed(sender, args) {

alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}

}

function generateexcel() {

for(z=0;z < gp_users.length;z++)
{
var table = document.getElementById(‘usrTable’);
var row = table.insertRow(1);
var cell1 = row.insertCell(0);

cell1.innerHTML =gp_users[z]

}
var x = document.getElementById(‘usrTable’).rows;
var xls = new ActiveXObject(“Excel.Application”);
xls.visible = true
xls.Workbooks.Add
for (i = 0; i < x.length; i++) {
var y = x[i].cells;
for (j = 0; j < y.length; j++) {
xls.cells(i + 1, j + 1).value = y[j].innerText;
}
}
window.location.href=”http://win-pfcp2dgt8di/sites/EnjoySharePoint/”;


}
</script>
<table id=”usrTable” border=”1″ style=”display:none;”>
<tbody>
<tr width=’250px’>
<th>Name</th>
</tr>
</tbody>
</table>

Hope this will be helpful.


You May Also like the Following SharePoint Online Tutorials:

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →