Difference between location.href and location.replace

D

It’s quite common to redirect a user visiting your webpage with javascript location href, 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 vs window.location.href


[code]window.location.href = ”;
[/code]

OR

[code]window.location.replace(”);
[/code]

Either of these JavaScript functions will redirect the user to the specified page by using the Javascript string replace() method, but what’s the difference? With the current document only one function will update the browser’s document history

Understanding this.location.href

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. Read on incase you encounter window.location.href window is not defined where location replace does not.

How does location.replace differ?

However, if you use the location.replace function (window location replace aka replace method) 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 replace function with the location object.

This would be important in the automatic redirect situation to update the session history, as clicking the Back button might keep the user in an endless back button loop.

Enjoy!

About the author

By Jamie

My Books