Firefox Addon - 从ActionButton访问预加载的内容脚本

时间:2014-08-12 20:59:19

标签: firefox firefox-addon content-script

我将内容脚本附加到我的firefox附加组件的每个标签上。

如果用户点击ActionButton(浏览器右上角的图标),我试图访问内容脚本处理函数,但它不起作用。

我正在使用来自Content Scripts的演练,但仍然无法使其发挥作用。

我做错了吗?

请参阅TODO下面的代码标记区域不起作用;

// main.js    
tabs.on('ready', function (tab) {
    var worker = tab.attach({
        include: "*",
        //contentScript: 'window.alert("Page matches ruleset");',
        contentStyleFile: [data.url("scripts/myTestContent1.js")]
    });
    worker.port.on('listener1', function (params) {
        // I will listen some messages coming from myTestContent1.js
    });   
    console.log("main.js: tab is ready!");
});



// browser icon typically at top right
var button = buttons.ActionButton({
    id: "myActionButton",
    label: "My pretty add-on",
    icon: {
        "16": "./icon-16.png",
        "32": "./icon-32.png",
        "64": "./icon-64.png"
    },
    onClick: handleClick
});

// when top right browser icon button is clicked
function handleClick(state) {
    var myWorker = tabs.activeTab.attach({
        //contentScriptFile: // I do not want to attach anything, just get Active tab!
    });
// TODO this code is not handled by active tab's content script
// should be handled by myTestContent1.js but does not work
    myWorker.port.emit("initialize", "Message from the add-on");
}

myWorker.port.emit 未在我的内容脚本上调用处理函数。

// myTestContent1.js    
// TODO this code is not calling :(
self.port.on("initialize", function () {
    alert('self.port.on("initialize")');

});

1 个答案:

答案 0 :(得分:1)

我通过跟踪制表符 - 工作人员对修复了问题,所以

var TabWorkerPair = function (tabid, worker) {
    this.tabid = tabid;
    this.worker = worker;
};

tabs.on('close', function (tab) {
    for (var i = 0; i < TabWorkerPairList.length; i++) {
        var pair = TabWorkerPairList[i];
        if (pair.tabid == tab.id) {
            // remove object from list
            TabWorkerPairList.splice(i, 1);
            break;
        }
    }
    console.log("main.js > tabs.on('close') > TabWorkerPairList count: " + TabWorkerPairList.length);
});


tabs.on('ready', function (tab) {
    var worker = tab.attach({
        include: "*",     
        contentScriptFile: [data.url("scripts/myTestContent1.js")]
    });
    // queue workers for tab
    var pair = new TabWorkerPair(tab.id, worker);
    TabWorkerPairList.push(pair);    
    console.log("main.js: tab is ready!");
});

最后我现在可以发出工作函数;

// when top right browser icon button is clicked
function handleClick(state) {    
    for (var i = 0; i < TabWorkerPairList.length; i++) {
        var pair = TabWorkerPairList[i];
        if (pair.tabid == tabs.activeTab.id) {
            pair.worker.port.emit("initialize", pair.tabid);
            break;
        }
    }

}

主要原因:标签可以包含多个工作人员。因此,您应该手动访问您感兴趣的工作人员。