JavaScript Redirects

11th March 2009

There are two main ways in which to redirect the browser using JavaScript, both of which look at the location of the window object. These are the location.href property and location.replace function.


The following example will cause the page to redirect to another page, keeping the browser history. This might seem like a minor point, but if you redirect a user to another page they will be able to click back, which will mean that they are redirected again.

  1. window.location.href="";


This works in the same way as location.href, but in this case the redirection will occur and no history will be kept in the browser. This means that if a user visits the page with this code on they will instead see a different page. This means that the user can't click on the back button and view the page that redirected them. Here is an example of its usage.

  1. <script type="text/javascript">
  2. <!--//--><![CDATA[// ><!--
  4. window.location.replace("");
  6. //--><!]]>
  7. </script>

You can also add this to a link by doing the following, although the user wouldn't be able to get back to the page that redirected them.

#! code

It should be noted here that you will probably want to avoid doing this sort of redirect unless you really have to. For example, if you relied on a JavaScript redirect in an important part of a form process and the user has JavaScript turned off then the process is quite likely to break. The ideal situation is to use server side scripts and redirect rules to force the browser to redirect in a more robust manner. Also, in terms of SEO using a JavaScript redirect is pointless as search engine spiders will probably not understand them.

Add new comment

The content of this field is kept private and will not be shown publicly.