window.location.href发生变化时的事件 [英] Event when window.location.href changes

查看:2264
本文介绍了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.

推荐答案

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)

所以,使用<$ 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发生变化时的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆