history.pushState does not trigger 'popstate' event

前端 未结 7 599
旧巷少年郎
旧巷少年郎 2020-12-16 12:13

Why

$(function () {
  $(window).bind(\'popstate\', function () {alert(\'pop\');});

  window.history.pushState(null, \'\', \'/foo\');
});

相关标签:
7条回答
  • 2020-12-16 12:18

    Document https://developer.mozilla.org/en-US/docs/Web/Events/popstate says:

    Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event will been triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in JavaScript).

    0 讨论(0)
  • 2020-12-16 12:21

    I ran into this too... I think the event only fires if you have something at the top level of your data object that is distinct from the previous state.

    Try this:

    var data = {rand: Math.random()};
    window.history.pushState(data, '', '/foo');
    
    0 讨论(0)
  • 2020-12-16 12:22

    You can manually trigger popstate event on window every time you call history.pushState().

    history.pushState(state, '', url);
    
    var popStateEvent = new PopStateEvent('popstate', { state: state });
    dispatchEvent(popStateEvent);
    
    0 讨论(0)
  • 2020-12-16 12:29

    Don't know exactly what you where trying to achieve but if you simply want your popState Event Handler to launch you can simply extract it out to a function like below :

    function popStateHandler(event) {
         // Event handling Code here
    }
    window.onpopstate = popStateHandler;
    

    Then you can simply call your popStateHandler after you pushState.

    0 讨论(0)
  • 2020-12-16 12:30

    My solution:

    var url = "http://awesome.website.net/route/to/paradise";
    window.history.pushState({}, "", url);
    window.history.pushState({}, "", url); // yes twice
    window.history.back();
    

    It will trigger a soft-navigation via 'popstate' event and no HTTP request.

    0 讨论(0)
  • 2020-12-16 12:31

    The paragraph you reference is a little ambiguous. Reading the example on the same page, it is clear that popstate is only triggered when the user clicks the back button, not when the script calls pushState().

    0 讨论(0)
提交回复
热议问题