JavaScript Redirect

Tuesday, May 1, 2012

There is an easy technique you can use in JavaScript to redirect your users. This may be helpful in a scenario where you are moving your website from an old domain to a new domain. There are many other methods you can implement to achieve the same goal, but we will go over how to do this using JavaScript code.

When your web page is moved, it would be a good idea to notify your visitors of the change. You can create add JavaScript code to your old home page, add a timer, and forward visitors to the new location of your website.

JavaScript window.location

We can control which page loads in the current window using the window.location property. By setting the window.location to a new URL, the visitor's web browser will load the new specified URL. Here is an example of how to redirect users. In the first example, we just assign the string value of the URL to the window.location property. In the second example, we use the location object's assign method. Both produce the same results.

<script type="text/javascript">
    window.location = ""

Include a Time Delay

It may confuse your visitors if they are immediately redirected to another page when visiting the old URL. Additionally, the time delay could be useful if you want to show a timer before a user is allowed to click on a link, or if you want to refresh the page on a routine cycle. Here is an example of how you would include a timer before redirecting a user to another page.

<script type="text/javascript">
  function delay() {
<body onLoad="setTimeout('delay()', 3000)">
<h2>Prepare to be redirected!</h2>
<p>See you at the new site!</p>


Location Object

The location object contains information about the current URL. The location object is part of the window object and is accessed through the window.location property.  The following properties and methods can be used for the location object.


hashReturns the anchor portion of a URL
hostReturns the hostname and port of a URL
hostnameReturns the hostname of a URL
hrefReturns the entire URL
pathnameReturns the path name of a URL
portReturns the port number the server uses for a URL
protocolReturns the protocol of a URL
searchReturns the query portion of a URL


assign()Loads a new document
reload()Reloads the current document
replace()Replaces the current document with a new one

You should note that there is no public standard that applies to the location object, but all major browsers support it.

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

Murachs JavaScript and DOM Scripting Professional JavaScript for Web Developers JavaScript and jQuery: The Missing Manual