22

I want to get the URL for my site collection. One way I thought I could do it was using the window.location in javascript and getting it that way.

I know that you can use ECMA script and the client object model to do this but unsure how.

I have tried:

var context = new SP.ClientContext;
alert(context.get_url());

This is returning /

How would I get it to include the full URL? i.e. http://mysharepoint:29292/

44

You can do it without any SharePoint calls by using the default JavaScript location object (W3schools) and the page variable _spPageContextInfo (Ted Pattison's Blog).

Something like:

var url = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
  • 1
    In my experience despite that this approach will work in a production environment, if you have a large team and you don't control their development environment @Matthias approach is better because it will work even when a developer is working with localhost. sharepoint.stackexchange.com/questions/24817/… – Roberto Alarcon Mar 5 '13 at 1:47
  • +1 for Exact Solution – Harsh Bhavsar Sep 30 '13 at 9:24
  • Great solution. Although I also needed the path to the current web which your solution didn't really take it all the way. But _spPageContextInfo.webServerRelativeUrl held what I was looking for. – Mohag519 Jan 20 '15 at 14:06
  • This wont work in 2007 will it? – Batman Jun 5 '16 at 16:21
14

You can do it like this:

<script>
function GetSiteUrl()
  {
    var ctx = new SP.ClientContext();
    var site = ctx.get_site();
    ctx.load(site);
    ctx.executeQueryAsync(function(s, a){alert(site.get_url())});
  }
</script>
<a href='javascript:GetSiteUrl();'>Get site URL</a>

To load only the URL from the site to minimize data traffic you can also call:

ctx.load(site, 'Url');

For more see reference: http://msdn.microsoft.com/en-us/library/ee538253.aspx

  • var siteUrl = site.get_url(); throws a SP.Res.propertyHasNotBeenInitialized exeception – John Dec 7 '11 at 14:28
  • I have updated the sample..., it works now. – Matthias Dec 7 '11 at 16:25
  • 1
    Just for John - the difference between normal SP object model programming and the Client object model is that nothing actually happens until ctx.executeQueryAsync - so in previous example you were asking for site properties while it was still 'null' (not strictly null but you get the idea) – Ryan Dec 7 '11 at 17:48
  • I had to add this code to Mattias' answer to get this all working: // Call function InitSiteUrl() after SP resources are loaded ExecuteOrDelayUntilScriptLoaded(InitSiteUrl, 'sp.js'); – samspot Mar 20 '12 at 17:18
12

You can do it in Singleline of code

var siteCollectionURL = _spPageContextInfo.siteAbsoluteUrl;
  • 1
    This is correct for SharePoint 2013, SP2010 _spPageContextInfo does not have the property siteAbsoluteUrl. – Anders Aune Feb 20 '15 at 10:54
3
function initialize()
    {
       var clientContext = new SP.ClientContext.get_current();
       siteCollec = clientContext.get_site();
       clientContext.load(siteCollec);
       clientContext.executeQueryAsync(Function.createDelegate(this, getUrl), Function.createDelegate(this, getFailed));
     }


function getUrl()
    {
       alert(site.get_url());
    }
    function getFailed()
    {
       alert('Failed to retrieve the server relative URL.');
    }
0

For this you can use any of the two:

var url = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;

Or we can use

var context = new SP.ClientContext();
var relativeWebUrl = context.get_url();
var fullWebUrl = window.location.protocol + '//' + window.location.host + relativeWebUrl ;
0

You can use the following:

For Site Collection URL:

var url = window.location.protocol + “//” + window.location.host + _spPageContextInfo.siteServerRelativeUrl;

For Sub Site URL:

var url = _spPageContextInfo.webAbsoluteUrl;
0

You can use the below code to find WebApp url, this takes care of port number too (if exists)

var WebAppUrl="";
if (location.port)
    {
        WebAppUrl = window.location.protocol + "//" + window.location.host + ":" + location.port;
    }
    else
    {
        WebAppUrl = window.location.protocol + "//" + window.location.host;
    }
0

I wanted to add another answer here as we've come into the age of the Sharepoint Add-In model and this won't work if you want to get the top level site collection from an Add-In, since you'll either be using a Provider Hosted add-in where your page is hosted off-site or Sharepoint Hosted add-in where it's hosted in the Add-In web. These answers will give you the URL for the Add-In web.

I got the top level site collection url from my Sharepoint Hosted add-in by using the following code:

//Get the URI decoded URLs.
hostweburl =
    decodeURIComponent(
        getQueryStringParameter("SPHostUrl")
);
// Set toplevelurl to the top level site collection url
toplevelurl = hostweburl.split("://")[0] + "://" + hostweburl.split("://")[1].split('/')[0];

Of course if you actually want to take any actions on the top level site collection, remember to use the Cross Domain Library, specifically SP.ProxyWebRequestExecutorFactory and SP.AppContextSite so something like:

clientContext = new SP.ClientContext(addinweburl);
var factory = new SP.ProxyWebRequestExecutorFactory(addinweburl);
clientContext.set_webRequestExecutorFactory(factory);
topContext = new SP.AppContextSite(clientContext, toplevelurl);

I won't go into using the CDL as that's covered well elsewhere and it's way beyond the scope of this question.

Hope this helps!

-1
<script language="javascript">
            _spBodyOnLoadFunctionNames.push("GrabUrl");
            function GrabUrl()
            {
                // Custom JavaScript methods
                var currentUrl = document.URL;
                alert(currentUrl);
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.