网页脚本和内容脚本以及main.js(附加代码)脚本之间的通信

时间:2014-04-28 19:40:12

标签: firefox firefox-addon firefox-addon-sdk

更新:抱歉,这个示例有效,我发现了一个小错误并修复了我的完整源代码。 但是我仍然想要一个比我更清楚的人就这个关于如何实现网页脚本和内容脚本与main.js(附加代码)脚本之间的通信的问题给出一个很好的答案,同时请回答我们如何访问localStorage从网页脚本和发送到附加脚本。


我无法找到如何正确建立之间的基本沟通:

页面脚本 - >内容脚本 - >附加脚本

反之亦然

附加脚本 - >内容脚本 - >页面脚本

enter image description here

请注意我理解页面脚本作为原始网页脚本,它不在沙箱中。 页面脚本来自网页标题:

<head>
<script type="text/javascript" src="http://www.domain.com/script.js"></script>
</head>

加载项脚本是main.js,内容文件 t附加了来自PageMod的contentScriptFile

这就是我所知道的。

我试过这个并且它无法正常工作:

main.js 加载项脚本:

 pageMod.PageMod({
    include: "*",
    contentScriptFile: self.data.url("content.js"),
    contentScriptWhen: 'ready',
    onAttach: function(worker) { 

        worker.port.on("message_from_content_script", function(data) { 
            worker.port.emit("message_to_page_script",mainStorage);
        });


     },
     attachTo: ["existing","top", "frame"]
  });

内容脚本:

document.addEventListener('DOMContentLoaded', function () { 


        self.port.emit("message_from_content_script", "some text");


});

如您所见,我到目前为止只尝试在内容脚本和附加脚本之间进行通信,但它无法正常工作。请有人给我看一个如何实现的例子:

页面脚本 - &gt;内容脚本 - &gt;附加脚本

反之亦然

附加脚本 - &gt;内容脚本 - &gt;页面脚本

1 个答案:

答案 0 :(得分:1)

how to communicate between page scripts and content scripts using custom DOM events上有大量文档,包括示例。

或者,您可以使用unsafeWindow,但可能有security issues,您的扩展程序可能会被addons.mozilla.org(AMO)拒绝