5.5.9.1 Event definitions
The popstate event is fired in certain cases when navigating to a session history entry.
According to this, there is no reason for popstate to be fired when you use pushState
. But an event such as pushstate
would come in handy. Because history
is a host object, you should be careful with it, but Firefox seems to be nice in this case. This code works just fine:
(function(history){
var pushState = history.pushState;
history.pushState = function(state) {
if (typeof history.onpushstate == "function") {
history.onpushstate({state: state});
}
// ... whatever else you want to do
// maybe call onhashchange e.handler
return pushState.apply(history, arguments);
};
})(window.history);
Your jsfiddle becomes:
window.onpopstate = history.onpushstate = function(e) { ... }
You can monkey-patch window.history.replaceState
in the same way.
Note: of course you can add onpushstate
simply to the global object, and you can even make it handle more events via add/removeListener
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…