Search code examples
javascriptfirefox-addonfirefox-addon-sdk

How do i reload contentScript (page-mod) on receiving a message?


I made an addon that creates a togglebutton and a panel attached to it, the panel has an enable/disable button, clicking the button will emit an "activate/deactivate" message to main.js.

When main.js receives the "deactivate" message it calls the destroy method on page-mod and the contentScript gets disabled and all changes made on the original document are restored.

However when main.js receives the activate message nothing happens, it creates the page-mod but it doesn't inject it to the target document unless i reload the page

How can i activate and inject the page-mod contentScript without reloading the page?

Main.js:

var { ToggleButton } = require('sdk/ui/button/toggle');
var panels = require("sdk/panel");
var self = require("sdk/self");
var tabs = require('sdk/tabs');
const { PageMod } = require("sdk/page-mod");

var button = ToggleButton({
    id: "my-button",
    label: "my button",
    icon: "./icon-16.png",
    onChange: function(state) {
        if (state.checked) panel.show({ position: {top: 10, right: 45} });
    }
});

var options = {
        include: "https://www.example.com/*",
        contentScriptWhen: "end",
        contentStyleFile: self.data.url("style.css"),
        contentStyle: ["rule1", "rule2", ...],
        attachTo : ["top"]
};

var mod = PageMod(options);

var panel = panels.Panel({
    contentURL: self.data.url("popup.html"),
    contentScriptFile: self.data.url("popup.js"),
    contentScriptWhen: "ready",
    onHide: function(){button.state('window', {checked: false});},
    onAttach: function() {
        panel.port.on('setStatus', function(status) {                   
            if (status && !mod) mod = PageMod(options);
            else {
                if (mod) mod.destroy();
                mod = null;
            }
        });
    }
});

Solution

  • options.attachTo = ["existing", "top"]