Why
$(function () { $(window).bind('popstate', function () {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?
html - history. pushState does not trigger 'popstate' event - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
The popstate event will be 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). Browsers tend to handle the popstate event differently on page load.
HTML DOM PopStateEvent Events that occur when the window's history changes.
In an HTML document, the history. pushState() method adds an entry to the browser's session history stack.
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);
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With