Search code examples
javascriptfirefoxfirefox-addonfirefox-addon-sdk

Firefox Add-on SDK Attach Content Script Once


var self = require("sdk/self");
var tabs = require("sdk/tabs");

var button = require("sdk/ui/button/action").ActionButton({
  icon: "./icon16.png", 
  label: "Test Button",
  onClick: function() {   
    tabs.activeTab.attach({
        contentScriptFile: ['./content.js']
    }); 
  }
});

I am attaching a content script file to the active tab by a toolbar button click.

How can I know if the content script is already attached to the activeTab or not? I do not want to add multiple content scripts to the tab. If there is any attached content script, I need to remove it.

Toggle button does not help me. Button does work tab specific way.


Solution

  • .attach returns a worker. Put it in a Map with the tab object as key. If there already is an entry present for that tab, don't attach.