Search code examples
javascriptweb-applicationsbrowser-history

why does history.replaceState() not work after history.go() method?


This is an example javascript code

function history() {
   window.history.pushState('','','#page1');
   window.history.pushState('','','#page2');
   window.history.pushState('','','#page3');
   window.history.go(-1);
   window.history.replaceState('','','#replaced');
}
// expected result in url is www.somewhere.com/#replaced
// but result is /#page2

Actually, I want to navigate first page and replace the history.state

Is there any idea to solve this problem?


Solution

  • It's because the history.go() method is asynchronous. The docs on MDN says this:

    This method is asynchronous. Add a listener for the popstate method in order to determine when the navigation has completed.

    So replaceState is executed before go(-1) is finished. That's what is causing the behavior.

    Use the popstate event in combination with the History API to go back and replace the correct state. The popstate event is triggered whenever you go back in the states that you have pushed to the history collection. Either using history.go(-1), history.back() or pressing the back button in the browser will trigger it.

    And if you are saying that you want to go back to the first page, then set the .go() value to -2, for you want to go back two places in the history.

    In the event listener check the location.hash value of the current location that you are in. This will let you know if you have reached the correct page. Then use replaceState to set the state correctly.

    window.addEventListener('popstate', function(event) {
      if (window.location.hash === 'page1') {
        window.history.replaceState('','','#replaced');
      }
    });
    
    window.history.pushState('','','#page1');
    window.history.pushState('','','#page2');
    window.history.pushState('','','#page3');
    window.history.go(-2);