Reputation: 861
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?
Upvotes: 0
Views: 61
Reputation: 33162
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);
Upvotes: 1