如何在contentScript

时间:2015-10-09 23:20:44

标签: javascript jquery firefox firefox-addon

我正在尝试绑定

self.port.emit()

到窗口中的事件,发信号通知我的pagemod(和页面工作者)做某事。但是,我没有尝试使用port.emit()函数。

index.js:

pageMod.PageMod({
  include: "*",
  contentScriptWhen: "ready",
  contentScriptFile: [
    data.url("jquery.js"),
    data.url("jquery-ui.min.js"),
    data.url("definitionsender.js"),
    data.url("define.js")
  ],
  onAttach: function(worker){
      contentScriptFile: [
        data.url("jquery.js"),
        data.url("jquery-ui.min.js"),
        data.url("define.js")
      ]
      worker.port.on("updatedWord", function(){
          console.log("success");
      });
    }
});

define.js:

$(window).dblclick(function() {
    var selected = getSelected();
    if (selected!="") {
    var completedURL = "http://www.dictionary.com/browse/" + selected;
    $('#define').dialog("open");
    dictionaryRef.contentURL = completedURL;
    self.port.emit("updatedWord");
    }
});

[编辑]:我通过我的代码返回,这3行实际上没有改变任何东西。但是,添加一个

var myScript = "window.addEventListener('dblclick', function() {" +
           "  var selection = window.getSelection().toString();" +
           "  if (selection != ''){" +
           "    self.port.emit('getWord', selection);" +
"}});"

作为pageMod的contentScript创建了一个工作的port.emit(),但后续的port.emit()和port.on()不起作用。

1 个答案:

答案 0 :(得分:2)

尝试:

pageMod.PageMod({
  include: "*",
  contentScriptWhen: "ready",
  contentScriptFile: [
    data.url("jquery.js"),
    data.url("jquery-ui.min.js"),
    data.url("definitionsender.js"),
    data.url("define.js")
  ],
  onAttach: function(worker){
      contentScriptFile: [
        data.url("jquery.js"),
        data.url("jquery-ui.min.js"),
        data.url("define.js")
      ]

      worker.port.on('dblclick', function(html) {
          console.log("success");
      });
    }
});

或者您应该使用:

index.js:

pageMod.PageMod({
  include: "*",
  contentScriptWhen: "ready",
  contentScriptFile: [
    data.url("jquery.js"),
    data.url("jquery-ui.min.js"),
    data.url("definitionsender.js"),
    data.url("define.js")
  ],
  onAttach: function(worker){
      contentScriptFile: [
        data.url("jquery.js"),
        data.url("jquery-ui.min.js"),
        data.url("define.js")
      ]
      worker.port.on("updatedWord", function(){
          console.log("success");
      });
    }
});

define.js:

$(window).dblclick(function() {
    var selected = getSelected();
    if (selected!="") {
        pageMod.port.emit("updatedWord");
    }
});