0

I am using the code below to get file-size of a remote file inside a Firefox Addon being developed using Mozilla Addon SDK.

main.js

// Import the page-mod API
var pageMod = require("sdk/page-mod");
// Import the self API
var self = require("sdk/self");


// Create a page mod
pageMod.PageMod({
    include : "*.example.com",
    contentScriptFile : [self.data.url("content.js"), self.data.url("jquery.min.js"), self.data.url("contentloaded.js")],
    contentScriptWhen : "ready",
    attachTo: ["top", "existing"],
    onAttach : startListening,
    contentScriptOptions : {
        iconWait : self.data.url("wait.gif"),
        iconFinished : self.data.url("done.png"),
    }
});

function startListening(worker) {


    worker.port.on("GetSize", function (data) {

        // Handle the message
        let getReq = require("sdk/request").Request({
                url : data[0],
                onComplete : function (response) {
                    reply = [response.headers["Content-Length"], data[1]];
                    //console.log("Send linkID : " + reply[1]);
                    worker.port.emit('receiveSize', reply);
                }
            }).head();
    });


}

This works perfectly but the the DisplaySize function gets called multiple times for the same request.

content.js

function checkURL(url, linkID) {

    data = [url, linkID];
    self.port.emit("GetSize", data);
    self.port.on("receiveSize", DisplaySize);
    console.log("Inside checkURL For linkID : " + linkID); //<--This displays only once for each request

}

function DisplaySize(data) {


    console.log("Inside DisplaySize For linkID : " + data[1]); //<--But this thrice

}

What am I missing here?

1 Answer 1

1

Each time you call port.on a new message listener is added. Only call it once.

function checkURL(url, linkID) {
    data = [url, linkID];
    self.port.emit("GetSize", data);
    console.log("Inside checkURL For linkID : " + linkID);
}

function DisplaySize(data) {
    console.log("Inside DisplaySize For linkID : " + data[1]);
}
self.port.on("receiveSize", DisplaySize);
Sign up to request clarification or add additional context in comments.

2 Comments

This solved it, however if I navigate to other pages (via Ajax) the previous message listener are still active resulting in same behavior. How to fix that?
nmaier any suggestions on how to get this fixed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.