HomeJavaScript Page 6 - Controlling Browser Properties with JavaScript
Location is Everything - JavaScript
Maybe you know how to make Web pages dance to your tune with JavaScript - but how about making the browser do the same? This tutorial focuses on the important browser objects (including the Window, Location and History objects) that are controllable via JavaScript, showing you how to manipulate and use them in your scripts.
If it's the browser URL you want to manipulate, you can't go wrong with the Location object, which exists under the Window object. This object has two important methods and three important properties - the latter are illustrated in the example below:
The "href", "host" and "protocol" properties of the Location object return the current URL, host name and protocol being used respectively. Of these, you can use the "href" property to redirect the browser to a new URL, simply by giving it a new value. The following example shows you how:
<script language="JavaScript"> // send browser to new URL window.location.href = "http://www.melonfire.com/"; </script>
An alternative way to accomplish the above is to redirect the browser to a new URL with the replace() method, as in the following example:
<script language="JavaScript"> // send browser to new URL window.location.replace("http://localhost/aa"); </script>
You can also refresh the page by reloading it with the browser's current URL with the reload() method. This method comes in particularly handy if you need to refresh a page at a pre-defined interval. Consider the following example, which illustrates: