Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

监听 history 的 push/replaceState 方法 #6

Open
nmsn opened this issue Nov 15, 2022 · 1 comment
Open

监听 history 的 push/replaceState 方法 #6

nmsn opened this issue Nov 15, 2022 · 1 comment

Comments

@nmsn
Copy link
Contributor

nmsn commented Nov 15, 2022

关键词:router、history、popstate

history.popstate 可以监听路由的变化,但只针对 history.go、history.back、history.forward 事件有效果

history.pushState 和 history.replaceState 没有相应的监听事件,如何实现?

@nmsn
Copy link
Contributor Author

nmsn commented Nov 15, 2022

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');

---

window.addEventListener('replaceState', function(e) {
  console.log('THEY DID IT AGAIN! replaceState');
});
window.addEventListener('pushState', function(e) {
  console.log('THEY DID IT AGAIN! pushState');
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant