Find a SharePoint Site Collection URL in Javascript

As a front-end dev at a Sharepoint shop, I often need to reference various components (images, paths, etc) that have paths relative to the site collection url. Using only javascript to parse the URL and then figure out where your site collection is can be tricky at best. What I typically do, is use a tiny bit of .NET in the master page to define some global variables I know I’ll need down the road.

The Code

Create your global javascript variable with the site collection url by dropping this snippet into your master page

<script type="text/javascript">
	var siteCollectionUrl = '<asp:Literal runat="server" Text="<%$SPUrl:~SiteCollection/%>"></asp:Literal>';

Then you have a nice global variable that you can reference inside other js files like so:

<script type="text/javascript">
  var newlink = siteCollectionUrl+"/path/to/file";


Anything you can put inside a tag can be printed out into a JS variable this way. So don’t think that this is the only cool little snippet you can include using this method. Important: make sure you give your variables very unique names, as you dont want them to conflict with any others in the global scope.


  1. Beautiful tip man… I was sweatin this one since I am loading HTML all over the place depending on what site collection you were on… this turned into a really nice way to handle it. Really appreciate it.

  2. Max M says:

    This is one solution. Another would be to use the L_Menu_BaseUrl variable where this information is saved.

    You can access this variable directly or change your siteCollectionUrl declaration to:

    var siteCollectionUrl = L_Menu_BaseUrl;

  3. Roopa says:

    @Max M: Thank you so much for that tip. So simple and so much helpful.

  4. suresh says:

    I have an issue if is possible to find site collection Name only but not URL in dynamically in sharepoint 2010.If it is possible please share me if nay information regards this issue.

Leave a Reply