How to redirect to another webpage in Javascript?

Javascript | redirect | assign | replace | how to

window.location.replace("<URL>") will best simulate an HTTP redirect.

  1. window.location.replace("<URL>") : Replace method, will replace the current page with the one provided in the input parameter. The current page will not be saved in the session, so you won't be able to go back in history using 'Back' button in the browser.

  2. window.location.assign("<URL>") : Assign method, will redirect to the given URL but it will keep in history original document, so you can navigate to the previous website using 'Back' button.

  3. window.location.href = "<URL>": Using location.href to redirect to the different document will also keep the browser history just like the assign method.

Which one to use?

If you want to simulate someone clicking on a link, use location.href

If you want to simulate an HTTP redirect, use location.replace

For example:

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";