Getting master page URL in SharePoint 2013 with JSOM

I’m only just starting to learn JSOM (after previously learning the server-side object model, and CSOM, via C#). There are some slightly weird requirements and limitations that are constantly tripping me up. Here’s today’s waste of time: trying to get the current site’s master page URL.

Here’s what I came up with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
        $(document).ready(function () {
            $('#divMain').text('Hello World.');
            getMasterUrl();
        });
        function getMasterUrl() {
            var myCtx = new SP.ClientContext();
            this.site = myCtx.get_site();
            this.web = myCtx.get_web();
            myCtx.load(web);
            myCtx.executeQueryAsync(
                Function.createDelegate(this, this.onSucceededMasterUrl),
                Function.createDelegate(this, this.onFailed)
                );
        }
 
        function onSucceededMasterUrl() {
            $('#divMain').text('Master URL: ' + web.get_masterUrl());
        }
        function onFailed(sender, args) {
            $('#divMain').text('Failed: ' + args.get_message());
        }

This just kept failing. I tried a bunch of random stuff to get it to work. In the end, I made a fairly minor change that got it to work. But then, I changed the code back, and it still worked. So this was going to be a post about a minor quirk of JSOM, but now it’s more of a “WTF” post. I’m sure I did something to make it work, and I just lost track of what it was. Well, either way, I’m having some fun with JavaScript.

Leave a Reply