Firefox扩展程序如何从内容脚本调用插件函数

4
我想从内容脚本中运行附加功能[main.js]。我阅读了火狐文档,但对我不起作用。这是关于脚本之间通信的官方文档https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts/using_port 这是我的 main.js 代码。
var tabs = require("sdk/tabs");
var data = require("sdk/self").data;

var pageMod = require("sdk/page-mod");
pageMod.PageMod({
  include: "http://mydomain/x.html",
  contentScriptFile: data.url("listen.js")
});

self.port.on("myAddonMessage", function(myAddonMessagePayload) {
  console.log("working");
});

这是我的listen.js内容脚本。
var myContentScriptMessagePayload="hi"; 
self.port.emit("myContentScriptMessage", myContentScriptMessagePayload);

实际上,我希望console.log("working");输出这个结果。但它没有工作。有人可以帮助我吗?我真的很困惑。实际上,我想从listen.js调用main.js函数。
1个回答

2

main.js 没有 self.port,content-scripts 才有。在 main.js 中,您需要使用与启动 content-script 的内容相应的端口。例如,PageMod 文档 中有更详细的信息。

var data = require("sdk/self").data;

var pageMod = require("sdk/page-mod");
pageMod.PageMod({
  include: "http://mydomain/x.html",
  contentScriptFile: data.url("listen.js"),
  onAttach: function(worker) {
    worker.port.on("myAddonMessage", function(myAddonMessagePayload) {
      console.log("working");
    });
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接