SharePoint 2013: How to get the site collection URL in JavaScript

by zebsadiq 4. May 2015 12:11

I often need to obtain the current site collection URL. Here is my little trick for doing so without loading SharePoint objects through the client context.

In memory intensive operations, its a good idea to think about performance and network traffic. Depending on what you are trying to achieve, you may find that you simply just want to obtain the URL to the site collection without needing any other information from the client context. There are a few ways of getting around, not having to load objects through the client context but here is one of my favourite tricks to achieve this.

As long you ensure that sp.js is loaded before executing the following lines, you will find that you can obtain the site collection URL via JavaScript without doing much work.

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

What is great about this is that it has minimal impact on performance compared to other methods and it works. Here are what the different segments of code mean:

  • window.location.protocol – gets the current protocol being used e.g http or https (handy if you have different environments using different protocols)
  • window.location.host  - Gets the domain level address of the url.
  • _spPageContextInfo.siteServerRelativeUrl – gets the relative site collection URL from the root of the domain address. e.g. If you are in the root site collection, this will return ‘/’ or if you are in a sub site collection, this will return ‘/sites/yoursitecollectionname/’.

Tags: , , ,

Cloud | JavaScript | SharePoint 2013

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Calendar

<<  March 2024  >>
MoTuWeThFrSaSu
26272829123
45678910
11121314151617
18192021222324
25262728293031
1234567

View posts in large calendar