history.pushState does not trigger 'popstate' event
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()
.
You are reading MDN's "guide page" which is not meant to be normative.
Consider reading MDN's "documentation page" for WindowEventHandlers.onpopstate
instead:
Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a clicking on the back button (or calling history.back() in JavaScript). And the event is only triggered when the user navigates between two history entries for the same document.
Another undocumented way of triggering popstate
is by direct manipulation of the window.location
object.
// this also triggers popstate
window.location.hash = "#some-new-hash"
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);