How to get notified about changes of the history via history.pushState?
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
I do this with simple proxy. This is an alternative to prototype
window.history.pushState = new Proxy(window.history.pushState, {
apply: (target, thisArg, argArray) => {
// trigger here what you need
return target.apply(thisArg, argArray);
},
});