如何在contentScript中使用port.emit()

How to use port.emit() in a contentScript

本文关键字:port emit contentScript      更新时间:2023-09-26

我正在尝试绑定一个

self.port.emit()

到窗口中的一个事件,以通知我的pagemod(和page-worker)做一些事情。但是,我尝试使用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");
    }
});

[EDIT]:我回顾了我的代码,这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()不能工作。

try:

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");
    }
});