问题
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