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

milan_9211 picture milan_9211 · Oct 9, 2011 · Viewed 107.5k times · Source

What is the difference between

  1. window.location.href="http://example.com";
  2. window.location.replace("http://example.com");
  3. 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");
}

<a onmouseover="fnSetVariable();" 
   href="PageCachingByParam.aspx?id=12" >
   CLICK 
</a>

Answer

Guffa picture Guffa · Oct 9, 2011

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 forums is not correct. The assign method does add a new record to the history.

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