What's the difference between window.location= and window.location.replace()?

Aaron Digulla picture Aaron Digulla · Dec 8, 2009 · Viewed 301.3k times · Source

Is there a difference between these two lines?

var url = "http://www.google.com/";
window.location = url;
window.location.replace(url);

Answer

cletus picture cletus · Dec 8, 2009

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;