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/

0

11 Answers 11

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;
4
  • 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/… Commented Mar 5, 2013 at 1:47
  • 1
    +1 for Exact Solution Commented Sep 30, 2013 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
    Commented Jan 20, 2015 at 14:06
  • This wont work in 2007 will it?
    – Batman
    Commented Jun 5, 2016 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

4
  • var siteUrl = site.get_url(); throws a SP.Res.propertyHasNotBeenInitialized exeception
    – John
    Commented Dec 7, 2011 at 14:28
  • I have updated the sample..., it works now.
    – Matthias
    Commented Dec 7, 2011 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
    Commented Dec 7, 2011 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
    Commented Mar 20, 2012 at 17:18
13

You can do it in Singleline of code

var siteCollectionURL = _spPageContextInfo.siteAbsoluteUrl;
1
  • 1
    This is correct for SharePoint 2013, SP2010 _spPageContextInfo does not have the property siteAbsoluteUrl. Commented Feb 20, 2015 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!

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);
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"

-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 and acknowledge you have read our privacy policy.

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