Search code examples
javascriptfirefoxfirefox-addonfirefox-addon-sdk

When i add contentscript using page-mod in firefox extension. The content script functions are executed thrice


I am unable to understand . Why my functions are executed thrice after addition in the firefox extension using "page-mod" .

This is my code : [main.js]

var pageModOptions = {
    include: ["http://xyz.com/*"],
    attachTo: ["top", "frame", "existing"],
    contentScriptWhen: "end",
    onAttach: function(worker){
        worker.port.on("Done", function(elementContent) {
            console.log("emitted by tarun :" + elementContent);
            worker.port.emit("start", htmlfilePath);
        });
    },
};

pageModOptions.contentScriptFile = [data.url("js/main.js"),data.url("js/jquery-1.8.2.min.js"),data.url("js/hello.js")];

//pageModOptions.contentScriptFile = data.url("js/jquery-1.8.2.min.js");
pageModOptions.contentStyleFile = data.url("js/main.css");
pageModOptions.contentScriptOptions = csOptions;
pageMod.PageMod(pageModOptions); 

and in the contentscript [hello.js]

function test(){
    window.alert('testing phase 1');
}
test();

So this alert is called thrice . How to stop this behaviour .


Solution

  • Your content script will run exactly once for each HTML document loaded from http://xyz.com/ - a separate instance of your content script will be injected into each of them. So seeing three alerts when this code runs can mean the following things:

    • There are three browser tabs open with pages from http://xyz.com/ loaded.
    • There is only one browser tab but the page from http://xyz.com/ loaded there includes two frames which are also loaded from http://xyz.com/.

    Most likely, if you change window.alert('testing phase 1') into window.alert(location.href) your confusion will be cleared up.