Difference between location.href and location.replace

Published on Feb 9, 2018 by Jamie Munro

It's quite common to redirect a user visiting your webpage, more specifically when they perform an action, such as: clicking a button. When the user completes the action and you want to redirect the user to somewhere else, you have two common choices:
window.location.href = '';


Either of these JavaScript functions will redirect the user to the specified page, but what's the difference?
When using location.href the current URL will be added to the user's navigation history. This means if they click the Back button, they will return to the page that performed the redirection.
However, if you use the location.replace function it will redirect the user, but not add the current page to the user's history. Thus when the user clicks the Back button they are returned to the page before the page that they were redirected from.
This would be important in the automatic redirect situation, as clicking the Back button might keep the user in an endless back button loop.

Tags: Javascript | JavaScript | location.href | location.replace

Related Posts

blog comments powered by Disqus