我无法在插件和附加脚本之间进行通信。 PageMod的附加事件有效但它不会将我的getElements
事件发送到我的list-getter。你如何正确使用port.emit
方法?谢谢!
index.js(插件)
var pageMod = require('sdk/page-mod');
var data = require("sdk/self").data;
pageMod.PageMod({
include: "*.workflowy.com",
contentScriptFile: [data.url("jquery-1.11.3.min.js"), data.url("list-getter.js")],
onAttach: function(worker) {
// For some reasong the worker doesn't emit?
worker.port.emit("getElements");
worker.port.on("gotElements", function(times) {
function printValues(el) {
console.log(el);
}
times.forEach(printValues);
});
}
});
list-getter.js(contentScriptFile)
self.port.on("getElements", function() {
var timeRegex = /\bam|pm/g
var openLists = $('.project.open').find('.content');
var times = []
for (var i = 0; i < openLists.length; i++) {
if (openLists[i].innerHTML.match(timeRegex)) {
times.push(openLists[i].innerHTML)
}
}
self.port.emit("gotElements", times);
});
答案 0 :(得分:0)
我犯了一个令人难以置信的错误。确保将数据对象加载的任何内容放在数据文件夹中。我有两份副本,正在改变错误的副本。感谢。
index.js
var pageMod = require('sdk/page-mod');
var data = require("sdk/self").data;
pageMod.PageMod({
include: "*.workflowy.com",
contentScriptFile: data.url("list-getter.js"),
onAttach: function(worker) {
worker.port.emit("getElements");
worker.port.on("gotElement", function(times) {
function printValues(el) {
console.log(el);
}
times.forEach(printValues);
});
}
});
列表getter.js
self.port.on("getElements", function(openProject) {
var times = []
var timeRegex = /\b([1-9]pm|[1-9]am|1[0-2]am|1[0-2]pm)/g;
var openLists = document.querySelectorAll('.content');
for (var i = 0; i < openLists.length; i++) {
if (openLists[i].innerHTML != "") {
if (openLists[i].innerHTML.match(timeRegex)) {
times.push(openLists[i].innerHTML);
}
}
}
self.port.emit("gotElement", times);
)};