Search code examples
javascriptfirefoxadd-oncontent-script

Content script cannot find created elements?


I'm trying to make the toolbar button (the browser toolbar) in my extension toggle a div on and off. However, I'm finding that the content script can't find any objects I create.

Here's the code where upon first click, the div is created. But upon 2nd click, it just creates another, when it should have found the last one and removed it:

main.js:

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

var button = require("sdk/ui/button/action").ActionButton({
  id: "style-tab",
  label: "Style Tab",
  icon: "./icon-16.png",
  onClick: function() {

    worker = tabs.activeTab.attach({
      contentScriptFile: self.data.url("my-script.js")
    });
    worker.port.emit("myaction", "whatever");
  }
});


my-script.js:

var div = 0;
self.port.on("myaction", function(color) {
    var el = document.getElementsByClassName("my-special-div");
    if (el.length) div = el[0];
    else div = 0;       

    if (!div) {
        // add div
        div = document.createElement("div");
        div.id = "my-special-div";
        document.body.appendChild(div);
    }
    else {
        document.getElementsByClassName("my-special-div")[0].remove();
    }
});

Any suggestions?

I guess the question can be posed more generally: how do I keep any state info about the things that are created in the content script that can also be accessed by the content script?


Solution

  • The code checks for a class but it sets the id. These are very different and if there might be more than one of these divs, then class is the correct property/attribute to use.

    my-script.js should be like:

    var div = 0;
    self.port.on ("myaction", function (color) {
        var el = document.getElementsByClassName ("my-special-div");
        if (el.length) div = el[0];
        else div = 0;       
    
        if (!div) {
            // add div
            div = document.createElement ("div");
            div.classList.add ("my-special-div")
            document.body.appendChild (div);
        }
        else {
            div.remove ();
        }
    } );