PageMod的Firefox Addon Attach事件不会发出事件

时间:2015-09-08 20:52:34

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

我无法在插件和附加脚本之间进行通信。 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);
});

1 个答案:

答案 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);
)};