Search code examples
javascriptfirefox-addonfirefox-addon-sdk

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);
});

Solution

  • 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");
    });