Welcome!

Apache Authors: Jnan Dash, Lacey Thoms, Sandi Mappic, Michael Bushong, RealWire News Distribution

Blog Feed Post

How to: Get a ClientContext for a site given a full URL

Last week, I was faced with the challenge of determining the URL to the site (web) when I knew the URL to a document in SharePoint.  I also happened to know the URL to the site collection, but I wanted to reliably get the URL to a web so I could get a ClientContext object for it.  Why would I want to do this?  Come to my session (#SPC3000) on Display Templates at #SPC14 to find out!  I also had someone leave a comment on my blog in just the last week about this topic, so I thought now would be a good time to share it.  @JThake suggested that he would have just parsed the path, but given a complex URL, that's not going to work!

With the server-side object model, you can pass a full URL to the SPSite constructor and get a reference to an SPWeb object.  This trick doesn't work though with JSOM.  If you want a reference to a given subsite, you need to pass the exact URL.  This technique wasn't obvious to me or a few others, but luckily @Path2SharePoint shed some light on this when he mentioned I needed to use /_api/contextinfo.  For those of you who have doing a lot with client side code you are probably familiar with this end point because you can get your form digest that way.  Honestly though, there is not a lot of information out there on this particular endpoint.

I did a search on the Internet to see if I could find a complete working example and things were pretty scarce.  Luckily though, I found a snippet on the bottom of a post from @Wictor that had just enough of what I needed.  Let's put it all together.  First let's assume we have a URL like the one below.  This refers to a document in buried in a folder of a document library of a subsite. 

var documentPath = "http://server/sitecollection/site/documents/folder/mydocument.docx";

We need to make a $.ajax() cal to the /_api/contextinfo end point, but first we need to assemble a URL that works.  To do this, we need to strip off the filename.  We'll then append our end point to the path.  We'll just use the substring function and lastIndexOf to split the path off.  If you have a library loaded to work with URLs, you can use one of those methods as well.

documentPath = documentPath.substring(0, documentPath.lastIndexOf('/')) + "/_api/contextinfo";

Now, we need to call $.ajax() to get the objects we need.  One thing to know is that this endpoint requires you to use POST instead of GET.  That means, you can't just try the URL in a web browser.  Here is what the code looks like.

$.ajax({

    url: docuemntPath,

    type: "POST",

    contentType: "application/x-www-url-encoded",

    dataType: "json",

    headers: {

        "Accept": "application/json; odata=verbose",

    },

    success: function (data) {

        if (data.d) {

            var webUrl = data.d.GetContextWebInformation.WebFullUrl;

 

            var clientContext = new SP.ClientContext(webUrl);

        }

    },

    error: function (err) {

       alert(JSON.stringify(err));

    }

);

In the success function, we can get the information we need from data.d.GetContextWebInformation.WebFullUrl.  This has the full path to the site hosting the document.  From there, we can just pass it to the constructor of SP.ClientContext to get a reference to that subsite.  Now you can work directly with the objects on that site such as it's lists or whatever you need.

We'll be using this snippet of code in my talk #SPC3000 at SharePoint Conference.  If you have an interest in display templates, be sure and attend!  Thanks again to everyone that helped me with this!

Read the original blog entry...

More Stories By Corey Roth

Corey Roth, a SharePoint Server MVP, is a consultant at Hitachi Consulting specializing in SharePoint and Office 365 for clients in the energy sector. He has more than ten years of experience delivering solutions in the energy, travel, advertising and consumer electronics verticals.

Corey specializes in delivering ECM and search solutions to clients using SharePoint. Corey has always focused on rapid adoption of new Microsoft technologies including Visual Studio 2013, Office 365, and SharePoint.

He is a member of the .NET Mafia (www.dotnetmafia.com) where he blogs about the latest technology and SharePoint. He is dedicated to the community and speaks regularly at user groups and SharePoint Saturdays.