我正在编写一个firefox插件,并且有一个内容脚本可以根据需要执行DOM操作,但是现在我想在操作的网页中显示插件数据目录中的一些图像(而不是在远程服务器上链接到它们)但我不确定该怎么做。

我看到附加模块和内容脚本之间的通信应该通过port.emit完成,但是API说该参数必须是JSON可序列化的。

有人做过吗?我觉得我错过了一些事情。

最佳答案

尽管您可以将resource: uri硬编码到数据目录中,但是最好在运行时构造它。这是在@loader/options伪模块的帮助下完成的,但是向前兼容的方式是通过self模块。如果没有其他原因使用port机制,则可以通过contentScriptOptions参数将uri传递到内容脚本。您的内容脚本可以从self.options访问它。以下代码将在mylogo.jpg域的每个页面上插入mozilla.org

// var options = require("@loader/options");
// options.prefixURI + options.name + "/data/" works now but may change in the future
var pageMod = require("sdk/page-mod");
var self = require("sdk/self");

pageMod.PageMod({
  include: "*.mozilla.org",
  contentScriptOptions: {prefixDataURI: self.data.url("")},
  contentScriptWhen: "ready",
  contentScript: "var img = document.createElement('img');" +
                 "img.src = self.options.prefixDataURI + 'mylogo.jpg';" +
                 "document.body.appendChild(img);"
});

10-02 17:54