我发送的信息是这样的:
self.port.emit("nodes_grubed", textNodesValues);
想对此做出反应:
worker.port.on("nodes_grubed", requestRenderedtext);
但它不起作用。我应该改变什么?您可以尝试我的加载项here。
main.js
:
var widgets = require("widget");
var tabs = require("tabs");
var self = require("self");
function requestRenderedtext(textNodesText) {
console.log('text nodes requesting');
}
var widget = widgets.Widget({
id: "mozilla-link",
label: "Mozilla website",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick:
function(worker) {
tabs.activeTab.attach({
contentScriptFile: self.data.url("process.js")
});
worker.on("nodes_grubed",requestRenderedtext);
worker.port.on("nodes_grubed",requestRenderedtext);
},
onAttach:
function(worker) {
worker.on("nodes_grubed",requestRenderedtext);
worker.port.on("nodes_grubed",requestRenderedtext);
}
});
widget.on("nodes_grubed",requestRenderedtext);
widget.port.on("nodes_grubed",requestRenderedtext);
process.js
:
function getTextNodes() {
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
null,
false
);
var node;
textNodes = [];
var textNodesValues=[];
while(node = walker.nextNode()) {
if (node.parentNode.tagName!='SCRIPT') {
textNodesValues.push(node.nodeValue);
textNodes.push(node)
}
}
if (textNodesValues.length!=0) {
console.log('emmiting nodes');
self.port.emit("nodes_grubed", textNodesValues);
}
}
getTextNodes();
答案 0 :(得分:2)
单击窗口小部件时,不会将worker作为参数(当单击发生时不存在) - 您可以通过调用tabs.activeTab.attach()
来创建它。您应该使用tabs.activeTab.attach()
的返回值,如下所示:
onClick:
function() {
var worker = tabs.activeTab.attach({
contentScriptFile: self.data.url("process.js")
});
worker.port.on("nodes_grubed", requestRenderedtext);
},