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

replaceState和pushState行为的监听

replaceState和pushState可以修改浏览器地址而不刷新界面,非常好用。但如果要实现浏览器的前进后退,页面也会变化,就需要对replaceState和pushState行为进行监听。此时,我们就得自己添加事件监听:
const bindEventListener = function(type) {
   const historyEvent = history[type];
   return function() {
       const newEvent = historyEvent.apply(this, arguments);
      const e = new Event(type);
       e.arguments = arguments;
       window.dispatchEvent(e);
       return newEvent;
   };
};
history.pushState = bindEventListener('pushState');
history.replaceState = bindEventListener('replaceState');
这样就创建了2个全新的事件,事件名为pushState和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');
});
这样就可以监听到pushState和replaceState行为。