Search code examples
javascriptfirefoxfirefox-addonfirefox-addon-sdk

Check if widget exists using addon sdk?


Goal is to check for a widget, and if it does not exist, create one, if it does exist, do nothing.

main.sj sets up a widget.
sends a message to content script.
content script checks for element with id of addon-widget but null is output, why?

var widgetObj = widget.Widget({
    id: "addon-widget",
    label: 'Hi',
    contentURL: Data.get("images/ico.png"),
    contentScriptFile: require("sdk/self").data.url("js/checkWidgetExistence.js")
}); 

widgetObj.port.emit("check", '');

js/checkWidgetExistence.js contains:

self.port.on("check", function () {

    console.log(document.getElementById("addon-widget"));
});

Why is null output on console?:

console.log: addon: null

Solution

  • You should be checking for the existence of the widget in the main script, not the content script. Content scripts are just for interacting with web pages.

    Widgets will be removed on uninstall, so if your add-on is installed and your code to create a widget works, then your widget will be there. I.E. if the above is true and your widget doesn't exist, neither does the code that checks its existence.

    You can still write code that checks for it, though. If widgetObj is a global variable, just use

    if (widgetObj) console.log("Widget exists");
    

    Otherwise use

    var doc = require("sdk/window/utils").getMostRecentBrowserWindow().document;
    if (doc.getElementById('addon-widget')) console.log("Widget exists");
    

    That said, the window utils module is a lower level module and I've read that its use could prevent your add-on from being approved by Mozilla unless it's absolutely necessary.