Search code examples
javascriptfirefox-addonfirefox-addon-sdkmessage-passing

Firefox SDK information from different contentscripts and main


Hopefully my question was not answered yet, since there are a lot of related Q&As.
First, this is my add-on structure:

addon/  
 data/  
  contentScript1.js  
 lib/  
  lib1.js  
 main.js  

Since the arrows are not working in markdown, I will describe it with words: add-on is the root, then two folders: data and lib and one file: main.js. Within data lies contentScript1.js and within lib lies lib1.js.

First I want to get a message from contentScript1.js, via port.on and port.emit:

//Part in main.js:  
var emitTest = "test";

pageMod.PageMod({
    include: "*",
    contentScriptFile: [self.data.url("contentScript1.js")],
    onAttach: function(worker) {
        worker.port.on("clicked", function (data) {
            if(data == "clickBox1"){
                console.log(data); //this works
                pageMod.PageMod({
                    include: "*",
                    contentScriptFile: [self.data.url("lib1.js")],
                    onAttach: function(worker2) {
                        worker2.port.emit("script2Test", "test");
                        worker2.port.emit("varTest", emitTest);
                        worker2.port.on("gotBack", function (data2) {
                            console.log(data2); //doesnt log
                        });
                    }
                });
            }
        });
    }
});

//Part in lib1.js:
self.port.on("script2Test", function(data) {
    self.port.on("varTest", function(data2) {
        self.port.emit("gotBack", functionInLib1(data, data2));
    });
});

I skipped the part of contentScript1.js, since the message passing between these two (contentScript1 and main) is working properly.

My question now is: Why is the marked console.log not working? I really tried to pass the messages right with port.on and port.emit...


Solution

  • Seems like you put lib1.js inside the lib folder instead of the data folder. Since you're using

    contentScriptFile: [self.data.url("lib1.js")],
    

    you should put the lib1.js in the data folder.