Get a Site Collection and Web Path Using JavaScript in SharePoint 2013

If you need to quickly get the site collection path or the specific web path of a current SharePoint 2013 site using JavaScript, use the _spPageContextInfo JavaScript object variable and its properties. A possible scenario includes creating a link to a library that may exist in every site and subsite of a particular site collection, but this link should be in the Master Page. In this case you will need the link url to include the particular web path of a given web. Or say you need the path to the site collection for a particular jQuery plugin you wish to use.

Site collection path:


Web path:


Be aware that _spPageContextInfo.webServerRelativeUrl will return the path without a trailing / at the end for sub webs. Consider a web url of http://yourdomain/subsite1. _spPageContextInfo.webServerRelativeUrl will return “/subsite1″ without a trailing “/”.

How about an example

Consider the path based site collection http://yourdomain/sites/hr and a sub web, http://yourdomain/sites/hr/onboarding.

Example URL: http://yourdomain/sites/hr/pages/default.aspx
_spPageContextInfo.siteServerRelativeUrl returns: /sites/hr
_spPageContextInfo.webServerRelativeUrl returns: /sites/hr

Example URL: http://yourdomain/sites/hr/onboarding/pages/default.aspx
_spPageContextInfo.siteServerRelativeUrl returns: /sites/hr
_spPageContextInfo.webServerRelativeUrl returns: /sites/hr/onboarding

We can extend this by saying you want to link to a particular web’s site contents, i.e. (path)/_layouts/15/viewlsts.aspx.

You could use the following code:

/*get the web’s path*/
var u = _spPageContextInfo.webServerRelativeUrl;

/*add a trailing / if one is not found, use for the root web of a url site collection, i.e. http://yourdomain/*/
if (u.length > 0) {if (u[u.length-1] != '/') u += '/';}

/*create a link to the current web's site contents*/
var siteContentsPath = u + '_layouts/15/viewlsts.aspx';

Note: This is also available in SharePoint 2010 but not SharePoint 2007 or earlier.

Note 2: The _spPageContextInfo JavaScript object is a really cool object that SharePoint provides to the client. Unfortunately I have not found good documentation on this from Microsoft. I normally use Firebug to investigate what SharePoint returns but there is a good post by Ted Pattison that I have found helpful.

Speak Your Mind


− six = 1