Thursday, March 20, 2014

Obtain the URL of your root website using Javascript

If you ever need to obtain the URL to your root website via Javascript code (i.e. http://rootWebsite), I've got a couple of good methods for doing so which are presented as follows:

If you're on a SharePoint site want to use CSOM:

var clientContext = new SP.ClientContext();
var rootWebsiteUrl = clientContext.get_site.get_rootWeb();


If you're on a SharePoint site and don't want to use CSOM:

var rootWebsiteUrl = _spPageContextInfo.siteServerRelativeUrl;


If you're not on a SharePoint site or, actually, have no idea what SharePoint is:

var currentLocation = document.location.toString();
var webApplicationNameIndex = currentLocation.indexOf('/', currentLocation.indexOf('://') + 3);
var rootWebsiteUrl = currentLocation.substring(0, webApplicationNameIndex);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.