简体   繁体   English

在附加脚本中的内容脚本中侦听消息

[英]Listen for message in content script from addon code

Addon code, 附加码,
Creates a Panel , populated by confirmPanel.html 创建一个Panel ,由confirmPanel.html填充
Listens for a getPreferences message from content script, 侦听来自内容脚本的getPreferences消息,
builds a JSON string and tries to send back to content script .. 构建一个JSON字符串,然后尝试发送回内容脚本..

var confirmPanel = require("sdk/panel").Panel({
    width: 450,
    height: 350,
    contentURL: Data.get("confirmPanel.html"),
});

confirmPanel.port.on("getPreferences", function() {

    var prefs = '{'
        +'"fileName":"HelloWorld.txt", '
        +'"pathToFile":"/home/rob/", '
        +'}';

    confirmPanel.port.emit("prefs", prefs);
})

confirmPanel.html specifies Panel contents .. confirmPanel.html指定Panel内容..

<html>
    <head>
        <script src="confirmPanel.js"></script>
    </head>
    <body onload="Addon_Panel.getPreferences()">
    </body>
</html>

confirmPanel.js is content script for confirmPanel.html confirmPanel.js是为内容脚本confirmPanel.html
Waits for body to load and then sends getPreferences message to addon code. 等待body加载,然后将getPreferences消息发送到附加代码。
Then waits for prefs message from addon code to log the JSON string to console 然后等待插件代码中的prefs消息将JSON字符串记录到控制台
but console.log(prefs); 但是console.log(prefs); is never executed? 永远不会执行?

var Addon_Panel = {

    getPreferences: function() {
        addon.port.emit("getPreferences", '');
    }
};

addon.port.on("prefs", function (prefs) {
    console.log(prefs);
});

Attached content script as file instead of including it in the html 将内容脚本附加为文件,而不是将其包含在html中
main.js main.js

var confirmPanel = require("sdk/panel").Panel({
    width: 450,
    height: 350,
    contentURL: Data.get("html/confirmPanel.html"),
    contentScriptFile: [Data.get("js/confirmPanel.js")]
});

confirmPanel.port.emit("prefs", prefs);

In content script file .. 在内容脚本文件中..

self.port.on("prefs", function (prefs) {
    console.log("in content script");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM