What's the best way to automatically redirect someone to another webpage?

// use this to avoid redirects when a user clicks "back" in their browser
window.location.replace('http://somewhereelse.com');

// use this to redirect, a back button call will trigger the redirection again
window.location.href = "http://somewhereelse.com";

// given for completeness, essentially an alias to window.location.href
window.location = "http://somewhereelse.com";

edit: looks like the user who posted the better answer has left SO, i've consolidated his answers here.


Most advised? To not do it. HTTP is far better suited to the job than JavaScript is (search engines follow them, you can state if it is permanent or not, they are faster, etc).

Failing that…

If you want an immediate redirect:

window.location.replace('http://example.com/');

This will replace the current URI with the new URI in the browser history, so the back button won't land the user on a page that immediately throws them forward again.

If you don't really want to redirect, but want to send the user somewhere in response to an event:

window.location.href = 'http://example.com/';

Remember to have a non-JavaScript fallback. A link is usually the best option, but it does depend on context.

Time delayed redirects are an even worse idea. The only reason to use them is if you want to display a message to the user - and users read things at different speeds (and have them sitting in another tab while they do something else). If the message is important enough to show, then it should be important enough to leave on screen until the user has read it and clicked a link to the next page.


One important thing to remember when redirecting a page using JavaScript is, always provide a non-JavaScript redirect as well! A link would do, or better a <META> tag, for example: <meta http-equiv="refresh" content="2;url=http://example.com">