Skip to main content

Change SharePoint/O365 MasterPage using JSOM

Here is one way to change the master page of a SharePoint site using JSOM, I have tested this in O365 site but it should work with on-prem version of SharePoint as well.

This code can be run on a script editor webpart and it works on the click of a html button control.

<script src="/_layouts/15/SP.Runtime.js" type="text/javascript"></script>
<script src="/_layouts/15/SP.js" type="text/javascript"></script>

<script type="text/javascript">

function ChangeMasterPage()
{
var customMasterPage = "/_catalogs/masterpage/Custom.master";
var siteRelativeUrl = _spPageContextInfo.siteServerRelativeUrl;
var clientContext;
var currentWeb;

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
clientContext = new SP.ClientContext.get_current();
currentWeb = clientContext.get_web();

currentWeb.set_customMasterUrl(siteRelativeUrl + customMasterPage);
currentWeb.set_masterUrl(siteRelativeUrl + customMasterPage);
currentWeb.update();

clientContext.load(currentWeb);

clientContext.executeQueryAsync(function () {
alert('MasterPage is changed successfully.');
        window.location.reload();            
    }, function (sender, args) {
        alert("Error: " + args.get_message());
    });

});
}
</script> ​​​​ ​​​

<input type="button" style="height:50px; width:200px; color:red;" value="Click Me" onclick="ChangeMasterPage();" />

Comments