Check if user exists before adding user to group - CSOM

Category: sharepoint 2010 customization


Jiniv Thakkar on Wed, 18 Jan 2017 14:07:24

Hi All,

I have implemented the following script, but I am unable to check if user exists in group before adding the user in group in the following script.

Please help 

var user;
var visitorsGroup;

function AddUsers()
//Load Current Site
var clientContext = new SP.ClientContext();

//Get all groups in site
var groupCollection = clientContext.get_web().get_siteGroups();
// Get the group by name
visitorsGroup = groupCollection.getByName('Approvers');
//ensure SP User
var usr2 = clientContext.get_web().ensureUser('domain\\loginname');
//Get all SP Users in SP Group
var userCollection = visitorsGroup.get_users();
//Add User to Group
var oUSR2 = userCollection.addUser(usr2);

//Load data
clientContext.load(oUSR2); clientContext.load(userCollection); 
//Execute Query
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

        function onQuerySucceeded() {

        function onQueryFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());

Thanks in Advance, Jiniv Thakkar


Lakshmanan Sethu on Wed, 18 Jan 2017 22:31:42


Here you go

Jiniv Thakkar on Fri, 27 Jan 2017 05:46:25

So I called this function to check if user exist

function IsCurrentUserMemberOfGroup(Uiduser)
             var grpName="Approvers";
             var userInGroup;
        var currentContext = new SP.ClientContext.get_current();
        var currentWeb = currentContext.get_web();

        var currentUser = Uiduser;

        var allGroups = currentWeb.get_siteGroups();

        var group = allGroups.getByName(grpName);

        var groupUsers = group.get_users();

        currentContext.executeQueryAsync(OnSuccess, OnFailure);

        function OnSuccess(sender, args)

            var groupUserEnumerator = groupUsers.getEnumerator();
            while (groupUserEnumerator.moveNext()) 
                var groupUser = groupUserEnumerator.get_current();
                var logingrpuser = groupUser.get_loginName();
                logingrpuser  = logingrpuser.split("i:0#.w|")[1];
                if (logingrpuser == currentUser) 
                    userInGroup = true;
            if (userInGroup) 
                     console.log("New user has been added");      



        function OnFailure(sender, args)
		console.log("Error in adding user in group");

where Uiduser = domain\loginName example : Uiduser = contoso\jinivthakkar

depending on flag condition, I can decide whether to call Add user function.