Follow @endyourif rss Facebook LinkedIn

Difference between location.href and location.replace Difference between location.href and location.replace

Published on Feb 9, 2018

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?

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

How does location.replace differ?

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

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP