Top Menu

Thursday, April 4, 2013

SharePoint Online - Change Master Page through CSOM

Scenario:
I had a requirement where one of our clients have a Team Site in SharePoint Online (Office 365) environment and the master page of that Team Site needs to be changed. 

Now the problem is _layouts/15/ChangeSiteMasterPage.aspx is not available in the Team Sites through Site Settings and Server Side code is not an option in SharePoint Online environment because Microsoft does not allow any server side deployment.

Solution:
The amazing Client-Side Object Model (JavaScript Object Model to be exact) saved the day. Here is the code:
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script> 
<script type="text/javascript" src="/_layouts/15/sp.js"></script> 
<script type="text/javascript">
    function ChangeMasterPage() {

        var context;
        var web;
        var strMasterPageUrl = '/_catalogs/masterpage/my_custom.master';

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

        web.set_customMasterUrl(strMasterPageUrl);
        web.set_masterUrl(strMasterPageUrl);
        web.update();

        context.executeQueryAsync(function () {

            alert("Master Page has been set to \n" + strMasterPageUrl);

        }, function (sender, args) {

            alert("Error: " + args.get_message());

        });
    }

    ChangeMasterPage();
</script> ​​​​ ​​​​

1 comment:

Official SharePoint Documentation

I have recently contributed to the official SharePoint documentation for developement. Check it out here: https://docs.microsoft.com/en-us...