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

July 26, 2019 No comments QA JavaScript Location

1. Introduction

In this article we will present the difference between location.replace, location.assign and location.href methods in JavaScript. All these three commands are used to redirect to another website but have a very different impact on the browser history.

2. 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.

Maybe a little example will clear this up:

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

in the above example 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.

3. 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.

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

in the above example pressing 'Back' button will redirect navigation to 'http://frontbackend.com' because assign method will not remove original page from history.

4. window.location.href = url;

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

5. Conclusion

Article described a difference between three redirect methods in JavaScript: location.replace, location.assign and location.href.

To simulate user click use location.assign() method or location.href property, this will keep full browser history.

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

{{ message }}

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