Issues with getting the SP.ClientContext in SharePoint 2013

So, I’m migrating a solution from SP2010 to 2013. In the JavaScript for part of the solution, I use the JavaScript client-side object model (JSOM). This involves getting the current ClientContext for the site:

var clientContext = new SP.ClientContext.get_current();

Unfortunately, ClientContext was null, so I kept getting Null Reference exceptions.

“Weird”, I thought, “This worked in 2010”. Now, my solution has a very similar piece of code elsewhere in it, so I went and tested it – and it worked. Even weirder.

Next up, I tried using a SP.SOD.executeOrDelayUntilScriptLoaded() call around the code where I got the ClientContext. Surely it was just a matter of waiting for the JavaScript file ‘sp.js’ to load? Well, it never loaded. With these two lines…

SP.SOD.executeOrDelayUntilScriptLoaded(function () { alert('SP.Runtme.js Loaded'); }, 'SP.Runtime.js');
SP.SOD.executeOrDelayUntilScriptLoaded(function () { alert('SP.js Loaded'); }, 'SP.js');

…no alerts were shown. On the page that works, they both get shown nearly instantly.

Okay, so it’s not my code then, it’s that the JSOM isn’t initializing, but only on one particular page. That sucks. What can I do to initialise it? Well, I found this post describing the same problem, but for publishing pages. Mine isn’t – it’s an application page – but I suspected it might be the same issue. And I checked MSDN which describes initialising sp.js.

I added this line:

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { });

And my code began working again on this page. So it seems that for some pages in SharePoint 2013 the Client Object Model isn’t necessarily initialized.

Advertisement
Issues with getting the SP.ClientContext in SharePoint 2013

2 thoughts on “Issues with getting the SP.ClientContext in SharePoint 2013

  1. Rangi says:

    Dude. Thanks heaps.
    Couldn’t get to the link you posted but your solution works for publishing pages.

  2. Murtuza says:

    Hi,

    This solution is working fine on the dedicated App page. But when I run this inside a page which is a client web part I.E. inside an app part. My SP.SOD itself is undefined.

    I tried adding init.js and sp.init.js

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.