24

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/

Eric Alexander
  • 43,293
  • 10
  • 53
  • 93
John
  • 3,763
  • 14
  • 58
  • 82

11 Answers11

51

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;
Phil Greer
  • 2,287
  • 9
  • 21
  • 23
Cas van Iersel
  • 776
  • 6
  • 5
  • 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. http://sharepoint.stackexchange.com/questions/24817/get-site-collection-full-url-using-javascript/24818#24818 – Roberto Alarcon Mar 05 '13 at 01:47
  • 1
    +1 for Exact Solution – Harsh Bhavsar Sep 30 '13 at 09: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 05 '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

Matthias
  • 2,087
  • 13
  • 22
  • var siteUrl = site.get_url(); throws a SP.Res.propertyHasNotBeenInitialized exeception – John Dec 07 '11 at 14:28
  • I have updated the sample..., it works now. – Matthias Dec 07 '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 07 '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
13

You can do it in Singleline of code

var siteCollectionURL = _spPageContextInfo.siteAbsoluteUrl;
Nishkalank
  • 331
  • 1
  • 3
  • 6
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.');
    }
Amit Kumawat
  • 6,689
  • 2
  • 22
  • 33
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 ;
Vishnu PS
  • 467
  • 4
  • 11
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;
Mancy Desaee
  • 1,817
  • 4
  • 23
  • 46
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;
    }
Taran Goel
  • 4,474
  • 5
  • 20
  • 44
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!

zpert
  • 151
  • 1
  • 3
0

No jQuery, no spContext. This can be used on a modern site. Probably needs some tweaking but the idea is to do it using a regex rather than any SharePoint or library provided object.

https://jsfiddle.net/4kz1wt3d/

function getSiteRelativeUrl(urlString) {
  var expr = "/sites/[A-Za-z0-9-]*"

  var match = urlString.match(expr);

  return match;
}

function getSiteAbsoluteUrl(urlString) {
  var expr = "https://[a-zA-Z.0-9]*"

  var matchFirstPart = urlString.match(expr);
  var relativeUrl = getSiteRelativeUrl(urlString);

    var ret = matchFirstPart + relativeUrl;

  return ret;
}

var url = "https://mySharePointSite.sharepoint.com/sites/WithumTest-022/sitepages/somepage.aspx"

var relativeUrl = getSiteRelativeUrl(url);
var absoluteUrl = getSiteAbsoluteUrl(url);

console.log(relativeUrl[0]);
console.log(absoluteUrl);
phil
  • 239
  • 1
  • 6
0

Site URL : _spPageContextInfo.siteAbsoluteUrl e.g. "https://site.sharepoint.com/sites/site1"

Page URL window.location.href e.g. "https://site.sharepoint.com/sites/site1/SitePages/Home.aspx"

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