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

Posted Wednesday, February 12, 2014 4:08 PM by CoreyRoth

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!

Comments

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

Wednesday, March 25, 2015 5:10 AM by Thomas Bomann

Nice article. Is there a way to accomplishing this with CSOM? I mean get ClientContext for a site given a full URL.

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

Tuesday, May 19, 2015 4:28 AM by Björn Roberg

Thank you very much for this article. Helped me!

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

Wednesday, January 25, 2017 8:10 AM by Steven von und zu Stevenson der 3.

thank You !

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

Monday, May 15, 2017 9:50 AM by Sergio Aguilar

I ran this script but it returns the site in where the script run, not the site of the document.

for example if you have a document URL:

mysharepoint.com/.../myDocument.docx

and run the script in

mysharepoint.com/.../mySubSite2

the ajax function return:

mysharepoint.com/.../mySubSite2

Leave a Comment

(required) 
(required) 
(optional)
(required)