Accessing Site Collection / Web properties and user Profile Properties in Javascript

Introduction

This time some findings related to JavaScript Object Model which I learn so I thought I should share this with all may be already shared by another techie. I’ll keep updating this blog as I’ll find new stuff related to JSOM.

  1. We have a requirement like to read the site collection properties in Java Script. First of all there is no property bag for SiteCollection. Those properties are stored in root web’s property bag.

    Following is the sample code for accessing web property in JavaScript. Following code will require SP.Js file to be loaded.
    1. //Make sure that the SP.js file is loaded   
    2. SP.SOD.executeOrDelayUntilScriptLoaded(getCustomWebProperty, 'SP.js');  
    3.   
    4. function getCustomWebProperty()  
    5. {  
    6.    var customWebProperty;  
    7.    //fetch the current context  
    8.    var context = SP.ClientContext.get_current();  
    9.    //fetch the all properties of current web  
    10.    allWebProperties = context.get_web().get_allProperties();  
    11.    context.load(allWebProperties);  
    12.    context.executeQueryAsync(  
    13.    function ()   
    14.    {  
    15.        //get specific property  
    16.        customWebProperty                      
    17.       = allWebProperties.get_fieldValues().myCustomWebProperty;  
    18.    });  
    19. }  
  2. Similarly we have also requirement to read the user profile property in JavaScript. One quick update here is we couldn’t update user profile properties from JavaScript, we can just read those.

    Following is the sample code for accessing web property in JavaScript.

    Following code will require SP.UserProfiles.Js file to be loaded.
    1. //Make sure that the SP.UserProfiles.js file is loaded   
    2. SP.SOD.executeOrDelayUntilScriptLoaded(getUserProfileProperty, 'SP.UserProfiles.js');  
    3.   
    4. function getUserProfileProperty()  
    5. {  
    6.    var customUserProfileProperty;  
    7.    var context = SP.ClientContext.get_current();  
    8.    //people manager provides methods for operation related to people  
    9.    var mgrPeople = new SP.UserProfiles.PeopleManager(context);  
    10.    //fetch the user properties of current user – Return Type: SP.UserProfiles.PersonProperties  
    11.    var myProps = mgrPeople.getMyProperties();  
    12.    context.load(myProps);  
    13.    context.executeQueryAsync(  
    14.    function ()   
    15.    {  
    16.        //fetch the user profile properties for the user.  
    17.        var profileProps = myProps.get_userProfileProperties();  
    18.       //fetch the specific property  
    19.       customUserProfileProperty =   
    20.       profileProps.MyCustomUserProfilePropertyName;  
    21.    });  
    22. }  

Thanks
Feel free to comment / feedback if any or if you have any query