1

我正在开发一个 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);
}

我也在与弹出脚本中的内容脚本进行通信,并且效果很好

4

0 回答 0