本文介绍了window.location.href发生变化时的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个站点编写一个Greasemonkey脚本,该站点在某些时候修改 location.href

I'm writing a Greasemonkey script for a site which at some point modifies location.href.

window.location.href 更改时,如何获取事件(通过 window.addEventListener 或类似的东西)页?我还需要访问指向新/修改的URL的文档的DOM。

How can I get an event (via window.addEventListener or something similar) when window.location.href changes on a page? I also need access to the DOM of the document pointing to the new/modified url.

我看过其他涉及超时和轮询的解决方案,但我想如果可能的话避免这种情况。

I've seen other solutions which involve timeouts and polling, but I'd like to avoid that if possible.

推荐答案

所以,使用<$ c时,听 popstate 事件并发送 popstate 事件$ c> history.pushState()应该足以在 href 更改:

So, listening to popstate event and sending a popstate event when using history.pushState() should be enough to take action on href change:

window.addEventListener('popstate', listener);

const pushUrl = (href) => {
  history.pushState({}, '', href);
  window.dispatchEvent(new Event('popstate'));
};

这篇关于window.location.href发生变化时的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:26