【问题标题】:Import a content script in a firefox extension without sdk在没有 sdk 的 Firefox 扩展中导入内容脚本
【发布时间】:2015-06-23 12:27:47
【问题描述】:

我正在尝试开发一个无需 sdk 的无需重启的 firefox 扩展,并且我希望能够操作页面的 DOM,但是文档、content.document 或 unsafeWindow.document 都返回未定义。

我的 bootstrap.js 代码:

Components.utils.import("resource://gre/modules/Services.jsm");
function startup(data,reason) {
    Components.utils.import("chrome://myextension/content/plugin-min.js");
}
function shutdown(data,reason) {
    Components.utils.unload("chrome://myextension/content/plugin-min.js");
}
function install(data,reason) { }
function uninstall(data,reason) { }

还有我的 plugin-min.js 代码:

document.addEventListener('keydown',activate); // document undefined
content.document.addEventListener('keydown',activate); // content undefined
unsafeWindow.document.addEventListener('keydown',activate); // unsafeWindow undefined

Mozilla 仅针对 SDK 用户发布了解决方案,而我所做的谷歌搜索仅带来了这些 SDK 解决方案。 :/

但就我而言,有人知道我缺少什么吗?

非常感谢。

【问题讨论】:

    标签: javascript firefox add-on


    【解决方案1】:

    主扩展脚本无法直接访问文档。您应该注入文档自己的内容脚本,并通过异步消息传递(端口对象)与之交换。

    此外,您可以提供一个上下文脚本数组 - 在这种情况下,所有这些都将被导入:

    var panel = panels.Panel({
            contentURL: self.data.url("page.html"),
            contentScriptFile: [self.data.url("script.js"), self.data.url('libs/jss.js')],
            contentStyleFile: self.data.url("style.css"),
            onHide: handleHide
        });
    

    不确定加载顺序,但在documentready 之后可以访问。

    更多阅读在official documentation

    【讨论】:

      猜你喜欢
      • 2022-08-13
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多