使用内容脚本时窗口中缺少属性

发布于 2025-01-03 22:42:27 字数 404 浏览 4 评论 0原文

我的插件正在将一些内容脚本注入到各个网站中。在尝试绑定 onbeforeunload 或调用 window.location.reload 后,我意识到 window 对象缺少一些属性。

有没有办法在通过 page-mod 模块注入代码时绑定某些事件(onbeforeunloadonunload 等)?

我创建了一个测试插件,显示缺少这些属性: https:// /builder.addons.mozilla.org/addon/1037497/latest/

有关如何使用它们的解决方案?

My addon is injecting some content scripts into various websites. After trying to bind onbeforeunload or calling window.location.reload I realized that the window object misses some properties.

Is there a way to binding certain events (onbeforeunload, onunload, etc) while injecting code via page-mod module?

I've created a test add-on, showing that these properties are missing: https://builder.addons.mozilla.org/addon/1037497/latest/

Solutions on how to use them anyway?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感性 2025-01-10 22:42:27

简短回答:您使用 addEventListener() 方法添加事件侦听器,如下所示:

window.addEventListener("beforeunload", function(event)
{
  ...
}, false);

长回答:出于安全原因,您的内容脚本不直接与 DOM 对象通信,例如它看不到任何脚本 -添加的属性。 技术细节还列出了一些限制:

分配或读取 XPCNativeWrapper 上的 on* 属性
DOM 节点或 Window 对象将抛出异常。 (使用
相反,使用 addEventListener ,并在您的代码中使用 event.preventDefault();
处理程序(如果您之前使用过 return false;)。)

在内容脚本中,您可能无论如何都不想替换网页的事件处理程序,而是添加您自己的事件处理程序 - 这就是 addEventListener()< /code> 正在做。

其他阅读

Short answer: You add an event listener using addEventListener() method, like this:

window.addEventListener("beforeunload", function(event)
{
  ...
}, false);

Long answer: For security reasons your content script isn't communicating with the DOM objects directly, e.g. it cannot see any script-added properties. The technical details also list some limitations:

Assigning to or reading an on* property on an XPCNativeWrapper of a
DOM node or Window object will throw an exception. (Use
addEventListener instead, and use event.preventDefault(); in your
handler if you used return false; before.)

In a content script you probably don't want to replace the web page's event handlers anyway, rather add your own - that's what addEventListener() is doing.

Additional reading

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文