我正在开发一个firefox插件作为Firefox WebExtention。我在使用后台脚本和弹出脚本传递消息时遇到问题。后台脚本可以读取所有消息,但弹出脚本无法从后台脚本中读取消息。
在后台脚本中传递组件的消息
var port = chrome.runtime.connect({name: "msgCon"});
chrome.runtime.onConnect.addListener(function(ports) {
ports.onMessage.addListener(handleMsg);
});
function handleMsg(msg){
console.log("message to background loging script: " +JSON.stringify(msg));
port.postMessage("msg from background script");
}

在弹出脚本中传递组件的消息
var port;
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
chrome.tabs.connect(tabs[0].id,{name: "msgCon"});
addPortListner();
});
function addPortListner() {
chrome.runtime.onConnect.addListener(function (ports) {
ports.onMessage.addListener(handleMsg);
port = ports;
});
}
function handleMsg(msg){
console.log("message to popup.js: " + JSON.stringify(msg));
}
function sendMeggage(msg){
port.postMessage(msg);
}

我还从弹出脚本中与内容脚本进行通信,效果很好