首页 > 建站教程 > JS、jQ、TS >  replaceState和pushState行为的监听正文

replaceState和pushState行为的监听

replaceState和pushState可以修改浏览器地址而不刷新界面,非常好用。但如果要实现浏览器的前进后退,页面也会变化,就需要对replaceState和pushState行为进行监听。此时,我们就得自己添加事件监听:
01const bindEventListener = function(type) {
02   const historyEvent = history[type];
03   return function() {
04       const newEvent = historyEvent.apply(this, arguments);
05      const e = new Event(type);
06       e.arguments = arguments;
07       window.dispatchEvent(e);
08       return newEvent;
09   };
10};
11history.pushState = bindEventListener('pushState');
12history.replaceState = bindEventListener('replaceState');
这样就创建了2个全新的事件,事件名为pushState和replaceState,我们就可以在全局监听:
1window.addEventListener('replaceState', function(e) {
2  console.log('THEY DID IT AGAIN! replaceState');
3});
4window.addEventListener('pushState', function(e) {
5  console.log('THEY DID IT AGAIN! pushState');
6});
这样就可以监听到pushState和replaceState行为。