How do you display only the webs the current user is a member of?

A common request from the customer is

“Can we display only the webs that the user is a member of?”

It’s not a easy thing to do (though it should have been?). You can use the “Follow site”-mechanism, or simple search showing the sites the user has access to, but that just doesn’t do it for the customer sometimes.

If you have a very shallow site hierarchy (maximum 1 level) with, let’s say 100 subsites, I’d say the simplest way is to use JS and the REST API. We’ll do a lot of REST API calls here, one for each web, plus the one to retrieve all the webs in the first place. You might get throttled! If you experience some serious throttling, do the queries in batches of 20 (How to: Avoid getting throttled or blocked in SharePoint Online).

We’ll have two functions:

  • LoadWebsWhereCurrentUserIsMember
  • GetMembersForWeb

We’ll make some calls to GetMembersForWeb() in our main function LoadWebsWhereCurrentUserIsMember().

So this is how we’ll do our JavaScript.

What we do in GetMembersForWeb is the following:

  1. For the web retrieved as a parameter
    1. We’ll do a call to /_api/web/associatedMemberGroup/Users
    2. Fetch the IDs from the arrays of object we retrieve
    3. Return a object with the SiteLogo, Title, URL and the array of User IDS

What we do in LoadWebsWhereCurrentUserIsMember is the following:

  1. Fetch all subwebs with a REST API call
  2. Fetch the current user id from _spPageContextInfo
  3. Create an array of functions (called promises)
  4. Loop through all the subwebs
    1. For each subweb
      1. Adds a call to our GetMembersForWeb() function with the subweb properties as parameter, to the function array promises
  5. When all the promises are done we’ll loop through all the subwebs again
    1. For each subweb
      1. If the user ID can be found in the Users object on the subwebs, we’ll add it to the DOM

NB! For on-prem you’ll need to add JSON-light support to use jQuery.getJSON

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s