htmlhistory.js

history.pushState does not trigger 'popstate' event


Why

window.addEventListener('popstate', () => alert('pop'));

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

does not alert pop ?

NB: Testing on latest chrome

--

According to MDN:

A popstate event is dispatched to the window every time the active history entry changes. If the history entry being activated was created by a call to pushState or affected by a call to replaceState, the popstate event's state property contains a copy of the history entry's state object.

So why my pushState does not trigger the popstate event?


Solution

  • 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().