Follow A SharePoint Site Using JavaScript Object Model

SharePoint 2016 provides better social experience features. We can follow the users and the sites, which we can see in the My Site personal page. In order to work with the social features, SharePoint has provided the SP.UserProfiles.js file. Before programmatically following a user or a site, we should ensure that SP.UserProfiles.js is loaded in the page.

In this blog, we will see how to programmatically follow a site, using JavaScript Object Model.

  1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
  2.     <script language="javascript" type="text/javascript">  
  3.     $(document).ready(function() {  
  4.         var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";  
  5.         $.getScript(scriptbase + "SP.Runtime.js", function () {  
  6.             $.getScript(scriptbase + "SP.js", function(){  
  7.                 $.getScript(scriptbase + "SP.UserProfiles.js", followSite);  
  8.             });  
  9.         }); 
  10.     });  
  11. var followingManager,actorInfo;  
  12. function followSite() {  
  13.   
  14.   
  15. //Get client context and social following manager object  
  16.     var clientContext = new SP.ClientContext();  
  17.     followingManager = new SP.Social.SocialFollowingManager(clientContext);  
  18.   
  19. // Create a SocialActorInfo object to associate the following site.  
  20.     siteActorInfo = new SP.Social.SocialActorInfo();  
  21.     siteActorInfo.set_contentUri("http://sharepoint2016/sites/HOL");  
  22.     siteActorInfo.set_actorType(SP.Social.SocialActorType.site);  
  23.     followingManager.follow(siteActorInfo);  
  24.   
  25. //Execute the batch  
  26.     clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
  27. }  
  28.   
  29. function QuerySuccess() {  
  30.     console.log("The site has been followed.");  
  31. }  
  32.   
  33. function QueryFailure(sender,args) {  
  34.     console.log('Request failed'+ args.get_message());  
  35. }  
  36. </script>  

We can add the code, given above to Content Editor Web part and see it in action. Going to the My Sites page, we can see the list of the sites, given below.


Summary

Thus, we saw how to follow a site in SharePoint Server 2016, using JavaScript Object Model.

Ebook Download
View all
Learn
View all