Search code examples
javascriptfirefoxfirefox-addonfirefox-sidebar

Firefox Add-on SDK: communicating objects between a sidebar and the main script


I am hacking away at my first addon, so the problem I am running into probably has either an obvious solution or my general approach is flawed.

I am using the Add-on SDK. My lib/main.js contains an object foo. The data directory has the files sidebar.html and sidebar.js. I want to pass foo to the sidebar-script and then change the sidebar depending on the state of foo. In the minmal example I will just try to display the object.

Minimal example:

main.js:

var foo = {"a": "b", "c": "d"};
var bar = require("sdk/ui/sidebar").Sidebar({
    id: "sb",
    title: "foobar",
    url: "./sidebar.html"
});
bar.show();

sidebar.html:

<!DOCTYPE html>
<html>
    <body>        
        <div id="foo-here">
            <!-- to be modified by sidebar.js -->
        </div>
    </body>
    <script type="text/javascript" src="sidebar.js"></script>
</html>

sidebar.js:

var foodiv = document.getElementById("foo-here");
var str = "", o;
// magically get foo from main.js here
for (o in foo) {
    if (foo.hasOwnProperty(o)) {
        str += "[" + o + " is " + foo[o] + "]";
    }
}
foodiv.innerHTML = str;

The sidebar docs explain how to listen for signals from the main script and call a function upon receiving a signal, but I can't figure out how to pass the object itself.


Solution

  • The port.emit() API mentioned in the sidebar docs you have linked also takes a second argument to pass in objects.