Changing Master Page Through CSOM in SharePoint 2013

SharePoint 2013 - Changing Master Page through CSOM

This article explains how to change a Master Page using JavaScript CSOM. In many cases, project requirements require us to use client scripting rather than server-side deployment. In one of my assignments, I was asked to change a MasterPage without involving the Farm administrator’s efforts and CSOM comes to the rescue. The following is the code snippet that does the job for us.

    <script>

        function MastePageChange() {
             var clientcontext;
            var cweb;
            var customMasterURL = '/_catalogs/masterpage/NewMasterPage';
            clientcontext = new SP.ClientContext.get_current();
            cweb = clientcontext.get_web();
            cweb.set_customMasterUrl(masterPageUrl);
            cweb.set_masterUrl(masterPageUrl);
            cweb.update();
            clientcontext.executeQueryAsync(function () {
               alert("Master Page has been changed successfully \n" + customMasterURL);
            }, function (sender, args) {
                alert("Error: " + args.get_message());
            });
        }
       MastePageChange();
    </script>