window.location.href 更改时的事件 [英] Event when window.location.href changes
问题描述
我正在为某个站点编写 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.
推荐答案
popstate 事件在活动历史记录条目更改时触发.[...] popstate 事件仅通过执行浏览器操作触发,例如单击后退按钮(或在 JavaScript 中调用 history.back())
The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)
因此,在使用 history.pushState()
时监听 popstate
事件并发送 popstate
事件应该足以对 <代码>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 更改时的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!