Get Current SharePoint Site Collection and Sub Site URL in Javascript

This is more of like self note article. I have been recently working on JavaScript CSOM and wanted to derive Current Site Collection and Sub Site URLs from the SP.JS objects.

For the site collections, it was interesting to see that SP.Web object has URL and ServerRelativeURL properties but it doesn’t have ParentWeb or RootWeb property which would allow me to traverse up to the tree to derive Site Collection URL.  As I was searching on web, I came across SharePoint Stack Exchange forum post where it was demonstrated how to derive current Site Collection URL by using default JavaScript location object (W3Schools) and the page variable _spPageContextInfo (Ted Pattison’s Blog).

It sounds like _spPageContextInfo gets added by SPWebPartManager which in turn gets added by default on majority of master pages. Since _spPageContextInfo object is already available on majority of SharePoint pages, you can just make following call sand it would return current site collection and sub site URLs.

For Site Collection URL =>  var url = window.location.protocol + “//” + window.location.host + _spPageContextInfo.siteServerRelativeUrl;

For Sub Site URL =>  var url = _spPageContextInfo.webAbsoluteUrl;

This has saved at least few hours for me and probably will save lot many hours in future as a reference. Nice trick to have in your bag as we are building lots of client side code blocks in SharePoint.

Additional References

Advertisements
This entry was posted in SP2010 DEV, SP2013 DEV. Bookmark the permalink.

One Response to Get Current SharePoint Site Collection and Sub Site URL in Javascript

  1. stanley1134 says:

    Thanks, I was searching for this and I got u r blog !!!!!!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s