Search code examples
sharepointsharepoint-2010

Get Current Users Group using the SP 2010 javascript Client Side Object Model


I am trying to obtain the current user's SharePoint group name that they belong to. I haven't been able to find a method/property that provides that information. I've only been able to get the current user's username. Is there a property that provides me this information that I am not seeing?


Solution

  • There is no direct method for returning the groups for the current user through javascript.

    Here is a post to an MSDN discussion group that describes a work around to return this information. If you want to know the group Name for checking permissions, a workaround is here.

    So basically:

    context = new SP.ClientContext.get_current(); 
    web = context.get_web();
    var value = web.get_effectiveBasePermissions();
    

    If you need the Group Name, unfortunately there is no direct way to do that. But we can get the current user and get user collection for one group. Then you can check the user collection from one group to see whether it contains the current user.

    1. Get current user: example

    2. Get group collection for the current web: example

    3. Get specified group

      var groupCollection = clientContext.get_web().get_siteGroups();
      // Get the visitors group, assuming its ID is 4.
      visitorsGroup = groupCollection.getById(4);
      
    4. Get users for the group

      var userCollection = visitorsGroup.get_users();
      
    5. Check the user collection to see whether it contains the specified user.

    For a simple demo you can see the following document.