原因
原生JavaScript 不支持,也无法直接监听 pushState 和 replaceState 事件。
解决方案
通过重写这两个 API 来实现调用可监听:
function getHandler(type) {
const func = history[type];
return function() {
const newFunc = func.apply(this, arguments);
const e = new Event(type);
e.stateInfo = {...arguments};
window.dispatchEvent(e);
return newFunc;
}
}
window.pushState = getHandler("pushState");
window.replaceState = getHandler("replaceState");
window.addEventListener("pushState", function(e) {
console.log("监听到pushState事件,传参为:", e.stateInfo);
})
window.addEventListener("replaceState", function(e) {
console.log("监听到replaceState事件,传参为:", e.stateInfo);
})
这样就可以直接调用window.pushState和window.replaceState了,在调用的同时也会打印出相应的日志