ResolveUrl in Javascript

This is something that is super easy, yet I get asked about it quite often.

Here’s how you do it:

In the master page for the site, put this:

<script type="text/javascript">
        var baseUrl = "<%= ResolveUrl("~/") %>";
</script>

Then, in your javascript file, put this function:

function ResolveUrl(url) {
    if (url.indexOf("~/") == 0) {
        url = baseUrl + url.substring(2);
    }
    return url;
}

 

You could have put the function right in the master page, but then you wouldn’t get intelli-sense on it for the rest of your code.

Now you can call ResolveUrl with ~/ right from javascript. 

Super easy, but also super useful!

If you use themes, you might even want to write something that does a “get themed url” where the current theme is output from the master page via Page.Theme.

 

more later – joel.

Published Friday, July 17, 2009 2:00 PM by joelvarty
Filed under: ,

Comments

# ResolveUrl in Javascript | ASP Scribe

Friday, July 17, 2009 3:10 PM by ResolveUrl in Javascript | ASP Scribe

Pingback from  ResolveUrl in Javascript | ASP Scribe

# re: ResolveUrl in Javascript

Friday, July 17, 2009 3:12 PM by David

Neat and nice time-saving trick!

Experienced some issues with placing it in the header (runat=server) but got it resolved here:

leedumond.com/.../the-controls-collection-cannot-be-modified-because-the-control-contains-code-blocks

# re: ResolveUrl in Javascript

Wednesday, August 19, 2009 4:57 AM by arandall

brilliant little tip, has really helped to clean up my Javascript code!  Definitely going to be using this a lot in the future.

Many thanks :)

# ASP.NET MVC Archived Buzz, Page 1

Sunday, January 31, 2010 5:48 PM by ASP.NET MVC Archived Buzz, Page 1

Pingback from  ASP.NET MVC Archived Buzz, Page 1

# re: ResolveUrl in Javascript

Monday, September 20, 2010 10:01 AM by vinay_jss

nice trick

# re: ResolveUrl in Javascript

Saturday, May 14, 2011 4:35 PM by Richard Lee

Oh, that is just beautiful - quick, clean and easy. Reduced the swearing level of my office by orders of magnitude I can tell you! (major pain when flicking between local IIS and production servers with the URL changing and making life real hard with subdirectories and JS files)

# re: ResolveUrl in Javascript

Monday, July 25, 2011 11:29 AM by David Carle

Thanks Joel

Beautifully simple.  Allows us to just get on with the coding rather than trying to force javascript to play nicely with asp.net

# Get Absolute Path of the Page URL Using Javascript - CodeDagger

Pingback from  Get Absolute Path of the Page URL Using Javascript - CodeDagger

Leave a Comment

(required) 
(required) 
(optional)
(required)