chrome扩展 - 在后台,内容脚本和弹出窗口之间传递消息

时间:2018-03-26 09:55:20

标签: javascript google-chrome-extension message

我的内容脚本代码包括:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log(message);
    console.log(sender);
});

chrome.runtime.onConnect.addListener((port) => {
    if (port.name === 'knock') {
        console.log(port);
        port.onMessage.addListener((msg) => {
            console.log(msg);
        });
    }
});

var port = chrome.runtime.connect({ name: 'knock' });

在后台

chrome.runtime.onConnect.addListener((port) => {
    if (port.name === 'knock') {
        console.log(port);
        port.onMessage.addListener(function (msg) {
            console.log(msg);
        });
    }
});

var port = chrome.runtime.connect({ name: 'knock' });

弹出

var port = chrome.runtime.connect({ name: 'knock' });
port.postMessage({ message: { success: true } });

后台环境成功接收并记录消息,而不运行任何内容脚本日志。我很困惑。我如何通过端口(建立长期连接)从后台,弹出窗口到内容脚本环境发送消息,反之亦然?

0 个答案:

没有答案