Wednesday, March 30, 2011

ECMAScript – Get Site Collection Server Relative URL

OBJECTIVE:
To programmatically obtain the Site Collection Server relative URL, with JavaScript Client Object Model.

INTRODUCTION:

One is working with the following Site Collection “http://myserver/mysitecollection “, and needs to get the Site Collection Server Relative Url “/mysitecollection “.

At the following link http://msdn.microsoft.com/en-us/library/ff458385.aspx, you can find a list of “substitution token”. For example, if you are working with Custom Action and you need to get the Current Web Url, you can use “{SiteUrl}”.
Unfortunately there isn’t a token to get the Site Collection Url.

SOLUTION:

SP.SOD.executeOrDelayUntilScriptLoaded(initialize,'SP.js');
function initialize()
{
var clientContext = new SP.ClientContext();
       var siteColl = clientContext.get_site();
       myweb = siteColl.get_rootWeb();
       clientContext.load(myweb);
       clientContext.executeQueryAsync(Function.createDelegate(this, getSiteCollectionUrl),  Function.createDelegate(this, getFailed));
}

function getSiteCollectionUrl()
{
var stUrl = myweb.get_serverRelativeUrl();
       alert(stUrl);
}
function getFailed()
{
alert('Failed.');
}

1 comment: