使用内容脚本时窗口中缺少属性
我的插件正在将一些内容脚本注入到各个网站中。在尝试绑定 onbeforeunload 或调用 window.location.reload 后,我意识到 window 对象缺少一些属性。
有没有办法在通过 page-mod
模块注入代码时绑定某些事件(onbeforeunload
、onunload
等)?
我创建了一个测试插件,显示缺少这些属性: 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短回答:您使用
addEventListener()
方法添加事件侦听器,如下所示:长回答:出于安全原因,您的内容脚本不直接与 DOM 对象通信,例如它看不到任何脚本 -添加的属性。 技术细节还列出了一些限制:
在内容脚本中,您可能无论如何都不想替换网页的事件处理程序,而是添加您自己的事件处理程序 - 这就是
addEventListener()< /code> 正在做。
其他阅读
Short answer: You add an event listener using
addEventListener()
method, like this: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:
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