Difference between window.location.href, window.location.replace and window.location.assign

Difference between window.location.href, window.location.replace and window.location.assign

What is the difference between

window.location.href=”http://example.com”;
window.location.replace(“http://example.com”);
window.location.assign(“http://example.com”);

I read in many forums that window.location.assign() just replaces the current session history and hence back button of browser will not function. However, I am not able to reproduce this.
function fnSetVariable() {
//window.location.href = “http://example.com”;
window.location.replace(“http://example.com”);
//window.location.assign(“http://example.com”);
}


CLICK

Solutions/Answers:

Solution 1:

These do the same thing:

window.location.assign(url);
window.location = url;
window.location.href = url;

They simply navigate to the new URL. The replace method on the other hand navigates to the URL without adding a new record to the history.

So, what you have read in those many forms is not correct. The assign method does add a new record to the history.

Reference: http://developer.mozilla.org/en/window.location

Solution 2:

The part about not being able to use the Back button is a common misinterpretation. window.location.replace(URL) throws out the top ONE entry from the page history list, by overwriting it with the new entry, so the user can’t easily go Back to that ONE particular webpage. The function does NOT wipe out the entire page history list, nor does it make the Back button completely non-functional.

(NO function nor combination of parameters that I know of can change or overwrite history list entries that you don’t own absolutely for certain – browsers generally impelement this security limitation by simply not even defining any operation that might at all affect any entry other than the top one in the page history list. I shudder to think what sorts of dastardly things malware might do if such a function existed.)

If you really want to make the Back button non-functional (probably not “user friendly”: think again if that’s really what you want to do), “open” a brand new window. (You can “open” a popup that doesn’t even have a “Back” button too …but popups aren’t very popular these days:-) If you want to keep your page showing no matter what the user does (again the “user friendliness” is questionable), set up a window.onunload handler that just reloads your page all over again clear from the very beginning every time.