How to: Work with Users and Groups Using JavaScript

Applies to: SharePoint Foundation 2010

The same data retrieval logic that applies to websites, lists, and list items in the JavaScript: SP namespace applies to users and groups. Like other objects in this namespace, you can use a CreationInformation object to create a user or group object.

Retrieving All Users from a SharePoint Group using ECMAScript (JavaScript, JScript)

The get_siteGroups function of the Web object gets all groups in all websites in a site collection. As shown in the following example, you can use the getById(id) function to return a specific group from the collection of groups. The get_users function of the Group object gets all the users in the group. Because the following example loads the users in the specified group, all properties of each user object are available.

var siteUrl = '/sites/MySiteCollection ';

function retrieveAllUsersInGroup() {

    var clientContext = new SP.ClientContext(siteUrl);
    var collGroup = clientContext.get_web().get_siteGroups();
    var oGroup = collGroup.getById(7);
    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();
        this.userInfo += '\nUser: ' + oUser.get_title() + 
            '\nID: ' + oUser.get_id() + 
            '\nEmail: ' + oUser.get_email() + 
            '\nLogin Name: ' + oUser.get_loginName();
    }
      
    alert(userInfo);
}

function onQueryFailed(sender, args) {

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

Retrieving Specific Properties of Users Using JavaScript

The following example modifies the previous example to return only the title and e-mail address of each user in a specific group. The example uses the Include statement to specify that only the title and email) properties are available on each user object, and calling other properties returns a PropertyOrFieldNotInitializedException.

var siteUrl = '/sites/MySiteCollection ';

function retrieveSpecificUserProperties() {

    var clientContext = new SP.ClientContext(siteUrl);
    var collGroup = clientContext.get_web().get_siteGroups();
    var oGroup = collGroup.getById(7);
    this.collUser = oGroup.get_users();
    clientContext.load(collUser, 'Include(Title, LoginName, Email)');


    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();
        this.userInfo += '\nUser: ' + oUser.get_title() + 
            '\nEmail: ' + oUser.get_email() + 
            '\vLogin Name: ' + oUser.get_loginName();
    }
        
    alert(userInfo);
}

function onQueryFailed(sender, args) {

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

Retrieving All Users in All Groups of a Site Collection Using JavaScript

The previous examples show how to return all users from a specified group. To return all users from all groups within a site collection, you can use the load(clientObject) function twice to load both the collection of groups and the collection of users in each group, in order to make all properties of each user and group available. Use LINQ query method syntax to include each user collection of each group, as in the following example.

var siteUrl = '/sites/MySiteCollection ';

function retrieveAllUsersAllGroups() {

    var clientContext = new SP.ClientContext(siteUrl);
    this.collGroup = clientContext.get_web().get_siteGroups();
    clientContext.load(collGroup);
    clientContext.load(collGroup, 'Include(Users)');

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

function onQuerySucceeded() {

    var userInfo = '';

    var groupEnumerator = collGroup.getEnumerator();
    while (groupEnumerator.moveNext()) {
        var oGroup = groupEnumerator.get_current();
        var collUser = oGroup.get_users();
        var userEnumerator = collUser.getEnumerator();
        while (userEnumerator.moveNext()) {
            var oUser = userEnumerator.get_current();
            this.userInfo += '\nGroup ID: ' + oGroup.get_id() + 
                '\nGroup Title: ' + oGroup.get_title() + 
                '\nUser: ' + oUser.get_title() + 
                '\nLogin Name: ' + oUser.get_loginName();
        }
    }
        
    alert(userInfo);
}

function onQueryFailed(sender, args) {

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

To improve efficiency, you can call the load(clientObject) function once and modify the query expression so that it includes only specific properties, as in the following example.

var siteUrl = '/sites/MySiteCollection ';

function retrieveAllUsersAllGroupsSpecificProperties() {

    var clientContext = new SP.ClientContext(siteUrl);
    this.collGroup = clientContext.get_web().get_siteGroups();
    clientContext.load(collGroup, 'Include(Title,Id,Users.Include(Title,LoginName))');

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

function onQuerySucceeded() {

    var userInfo = '';

    var groupEnumerator = collGroup.getEnumerator();
    while (groupEnumerator.moveNext()) {
        var oGroup = groupEnumerator.get_current();
        var collUser = oGroup.get_users();
        var userEnumerator = collUser.getEnumerator();
        while (userEnumerator.moveNext()) {
            var oUser = userEnumerator.get_current();
            this.userInfo += '\nGroup ID: ' + oGroup.get_id() + 
                '\nGroup Title: ' + oGroup.get_title() + 
                '\nUser: ' + oUser.get_title() + 
                '\nLogin Name: ' + oUser.get_loginName();
        }
    }
        
    alert(userInfo);
}

function onQueryFailed(sender, args) {

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

Adding a User to a SharePoint Group Using JavaScript

If the user object that you want to add to a group already exists within the site collection, you can use the addUser(user) function to add the user to the user collection of the group. But if the user does not already exist, as in the following code example, use the UserCreationInformation object to define a new user, and then add the new user to the group's user collection through the add(parameters) function. This example uses the getById(id) function to return a specific group from the collection of groups within the site collection, then defines a new user object, and adds it to the user collection of the group.

var siteUrl = '/sites/MySiteCollection ';

function addUserToSharePointGroup() {

    var clientContext = new SP.ClientContext(siteUrl);
    var collGroup = clientContext.get_web().get_siteGroups();
    var oGroup = collGroup.getById(7);
    var userCreationInfo = new SP.UserCreationInformation();
    userCreationInfo.set_email('alias@somewhere.com');
    userCreationInfo.set_loginName('DOMAIN\alias');
    userCreationInfo.set_title('John');
    this.oUser = oGroup.get_users().add(userCreationInfo);
    
    clientContext.load(oUser);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}

function onQuerySucceeded() {
        
    alert(this.oUser.get_title() + " added.");
}

function onQueryFailed(sender, args) {

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

See Also

Concepts

How to: Work with Roles Using JavaScript

How to: Break Role Assignment Inheritance Using JavaScript

Data Retrieval Overview

SharePoint Client Object Creation

SharePoint 2010 Client Object Model Guidelines

Common Programming Tasks in the JavaScript Object Model

Other Resources

JavaScript Class Library