Firefox port.emit and port.on not working in extension

青春壹個敷衍的年華 提交于 2020-02-04 04:07:49

问题


I am trying to make a firefox extension. I need to exchange data with the background script(main.js) so I am trying to use port but it doesn't work.

//Content.js
self.port.on("alert",function(){alert()});//Listen to message 
self.port.emit("message",{message:"Hello"});

And in the main.js this is how I add the worker. So bascically, when the content script sends "message", the background script sends "alert" and the content script alerts. That doesn't happen

//main.js

pageMod.PageMod({
  include: ["https://play.google.com/*"],
  contentScriptWhen: 'ready',
  contentScriptFile: [data.url("jquery.js"),data.url("jquery.knob.js"),data.url("purl.js"),data.url("content.js")],
  contentScriptOptions: {
    inUrl: data.url("in.png"),
    outUrl: data.url("out.png"),
    logoUrl: data.url("logoimage.png")
  },
  contentStyleFile: [data.url("css/inject.css")],
  onAttach: function(worker) {//Ttach
    alert("hello there")
    worker.on("message",function(){

        worker.emit("alert",{message:"Hello"});
    })

  }
});

Nothing happens at all. i have no way of knowing whether hte first message is sent(cotnent script to extension). What am I doing wrong?


回答1:


The code should have been worker.port.emit and worker.port.on instead of worker.on and worker.emit

pageMod.PageMod({
  include: ["https://play.google.com/*"],
  contentScriptWhen: 'ready',
  contentScriptFile: [data.url("jquery.js"),data.url("jquery.knob.js"),data.url("purl.js"),data.url("content.js")],
  contentScriptOptions: {
    inUrl: data.url("in.png"),
    outUrl: data.url("out.png"),
    logoUrl: data.url("logoimage.png")
  },
  contentStyleFile: [data.url("css/inject.css")],
  onAttach: function(worker) {//Ttach
    alert("hello there")
    worker.port.on("message",function(){
//THIS IS THE CORRECT CODE
        worker.port.emit("alert",{message:"Hello"});
    })

  }
});


来源:https://stackoverflow.com/questions/20868824/firefox-port-emit-and-port-on-not-working-in-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!