Wednesday, 1 August 2012

About URLs in Javascript

How to Retrieve the Current URL in Javascript?

This is how to retrieve the current entire URL (for example: http://www.mywebsite.com/somepage.html):

  alert( window.location.href );

For the path relative to the host (/somepage.html):

  alert( window.location.pathname );

For the host name (www.mywebsite.com):

  alert( window.location.hostname );

For more options, see this Mozilla page.

Is There Any Difference between window.location and document.location?

In Javascript today, there is no difference between both, but the recommended way to retrieve the current location object is window.location.

Using document.location used to return a string rather than an object. This may be an issue with old browsers if code expects an object.

How to Change the Current Page/URL from Javascript?

Simply assign the new URL value as following:

  window.location.href = newURLvalue;

How to Detect Whether One is On Production Server?

There are situations (for example with ShareThis Buttons or Google Advertising), where the corresponding Javascript will not execute properly on localhost, therefore preventing the HTML page from being displayed properly. One needs conditional execution of Javascript.

Assuming that the server's hostname is (for example) www.prod.com, we can retrieve it and check against it:
if ( window.location.hostname == 'www.prod.com' ) {
  alert("We are on production!");
} else {
  alert("We are not on production!");
}