js:如何监听history的pushState方法和replaceState方法。(高阶函数封装+自定义事件)
作者:互联网
出现原因:
想要监听路由变化就需要监听history的pushState和replaceState事件,但是原生并没有支持,此时,我们就得自己添加事件监听。
解决方法:
高阶函数封装自定义事件:
const bindHistoryEvent = function(type) {
const historyEvent = history[type];
return function() {
const newEvent = historyEvent.apply(this, arguments); //执行history函数
const e = new Event(type); //声明自定义事件
e.arguments = arguments;
window.dispatchEvent(e); //抛出事件
return newEvent; //返回方法,用于重写history的方法
};
};
重写history原有的方法:
history.pushState = bindHistoryEvent('pushState');
history.replaceState = bindHistoryEvent('replaceState');
监听事件:
window.addEventListener('replaceState', function(e) {
console.log('THEY DID IT AGAIN! replaceState');
});
window.addEventListener('pushState', function(e) {
console.log('THEY DID IT AGAIN! pushState');
});
标签:function,replaceState,const,自定义,js,pushState,监听,history 来源: https://blog.csdn.net/qq_44697303/article/details/120412469