简体   繁体   中英

Listen for message in content script from addon code

Addon code,
Creates a Panel , populated by confirmPanel.html
Listens for a getPreferences message from content script,
builds a JSON string and tries to send back to content script ..

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 ..

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

confirmPanel.js is content script for confirmPanel.html
Waits for body to load and then sends getPreferences message to addon code.
Then waits for prefs message from addon code to log the JSON string to console
but 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
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");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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