Why
$(function () {
$(window).bind(\'popstate\', function () {alert(\'pop\');});
window.history.pushState(null, \'\', \'/foo\');
});
Document https://developer.mozilla.org/en-US/docs/Web/Events/popstate says:
Note that just calling
history.pushState()
orhistory.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 callinghistory.back()
orhistory.forward()
in JavaScript).
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');
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);
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.
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.
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()
.