JavaScript Redirects

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.

location.href

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.

<script type="text/javascript">
window.location.href="http://www.hashbangcode.com/";
</script>

location.replace

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.

<script type="text/javascript">
window.location.replace("http://www.hashbangcode.com/");
</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.

<a href="javascript:window.location.replace('http://www.hashbangcode.com/')" title="#! code">#! code</a>

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.
CAPTCHA
3 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.