What is the difference between location.replace, location.assign and location.href?

October 15, 2018 No comments QA JavaScript Location

All these three commands are use to redirect to another webpage but have a very different impact on the browser history.

1. window.location.replace(url)

Replace method, will replace the current page with the one provided in the parameter. The current page will not be saved in session, so you won't be able to go back in history using 'Back' button in the browser.

Maybe little example will clear this up to you:

document.location.href = 'http://google.com'; // go to google website
document.location.href = 'http://frontbackend.com'; // go to frontbackend homepage
document.location.replace('http://frontbackend.com/Frontend');  // replace to another webpage
// pressing 'Back' button on the browser will go back to http://google.com, because url http://frontbackend.com was replaced with http://frontbackend.com/Frontend without saving history.

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 webpage using 'Back' button.

Example:

document.location.href = 'http://google.com'; // go to google website
document.location.href = 'http://frontbackend.com'; // go to frontbackend homepage
document.location.assign('http://frontbackend.com/Frontend'); // loads a new page
// press 'Back' button and you will be redirected to 'http://frontbackend.com' because assign method will not remove original page from history

3. window.location.href = url;

Using location.href to redirect to the different document will also keep the browser history just like assign method.

So if you want to simulate user click use location.assign() method or location.href property, this will keep full browser history.

If you want to simulate HTTP redirect use location.replace() - this will replace previous item in the history of your browser session.

{{ message }}

{{ 'Comments are closed.' | trans }}