【问题标题】:Multiple messages from main script to contentscript从主脚本到内容脚本的多条消息
【发布时间】:2015-02-11 14:15:34
【问题描述】:

我正在使用下面的代码来获取正在使用Mozilla Addon SDK 开发的Firefox Addon 中的远程文件的文件大小。

ma​​in.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();
    });


}

这很好用,但 DisplaySize 函数会为同一个请求多次调用。

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

}

我在这里错过了什么?

【问题讨论】:

    标签: javascript jquery firefox firefox-addon firefox-addon-sdk


    【解决方案1】:

    每次调用port.on 时都会添加一个新的消息侦听器。只调用一次。

    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);
    

    【讨论】:

    • 这解决了它,但是如果我导航到其他页面(通过 Ajax),之前的消息侦听器仍然处于活动状态,从而导致相同的行为。如何解决这个问题?
    • nmaier 关于如何解决这个问题有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2013-05-03
    • 1970-01-01
    相关资源
    最近更新 更多