Javascript 使用chrome扩展,如何使用长期连接(端口)将消息从后台脚本传递到内容脚本?

Javascript 使用chrome扩展,如何使用长期连接(端口)将消息从后台脚本传递到内容脚本?,javascript,google-chrome-extension,Javascript,Google Chrome Extension,这是我的背景脚本。我能够从弹出脚本向它发送消息。换句话说,控制台在后台页面中记录“hello” // background.js chrome.runtime.onConnect.addListener(function(port){ port.onMessage.addListener(function(msg) { if (msg.greeting == "hello") { var port = chrome.tabs.connect

这是我的背景脚本。我能够从弹出脚本向它发送消息。换句话说,控制台在后台页面中记录“hello”

// background.js

chrome.runtime.onConnect.addListener(function(port){

    port.onMessage.addListener(function(msg) {

        if (msg.greeting == "hello") {

            var port = chrome.tabs.connect(0, {name: "mycontentscript"});

            port.postMessage({greeting:"hello"});

            console.log('hello');
        }
    });
});
但是,我无法将消息从后台脚本获取到我的内容脚本。这是我的内容脚本。警报没有显示

// content.js

var port = chrome.runtime.connect({name:"mycontentscript"});

port.onMessage.addListener(function(message,sender){

    if (message.greeting == "hello") {

        alert('hello');
    }
});

我做错了什么?谢谢。

我不知道我的情况是否与你的情况完全相同,但我还编写了一个Chrome扩展,其中后台页面向客户端发送消息

在我的示例中,我执行以下操作:

chrome.runtime.sendMessage('requestData', this.updateData.bind(this));
在我看来,我有:

然后我的内容脚本接收到消息:

this.updateData = function(data) {
    //...
}
希望这对你有帮助

在background.js中:

chrome.runtime.onConnect.addListener(function(port){//here you've got the port

    port.onMessage.addListener(function(msg) {

        if (msg.greeting == "hello") {
//and here you're making a new, unneeded port, for which nobody is listening. 
//Use the one you've got.
            var port = chrome.tabs.connect(0, {name: "mycontentscript"});

            port.postMessage({greeting:"hello"});

            console.log('hello');
        }
    });
});
使用chrome.tabs.connect从后台启动连接,并将chrome.runtime.onConnect侦听器放在选项卡的content.js中,或者像您所做的那样从选项卡启动连接,并使用在后台的onConnect侦听器中获得的端口。把它删掉

var port=chrome.tabs.connect(0,{name:“mycontentscript});


行。

似乎您忘记了建立连接,只是在创建端口后在内容脚本中使用
postMessage
,然后在后台页面中的
runtime.onConnect.addListener()中重用端口

// background.js

chrome.runtime.onConnect.addListener(function(port){

    port.onMessage.addListener(function(msg) {

        if (msg.greeting == "hello") {

            var port = chrome.tabs.connect(0, {name: "mycontentscript"});

            port.postMessage({greeting:"hello"});

            console.log('hello');
        }
    });
});
background.js

chrome.runtime.onConnect.addListener(function(port) {
    port.onMessage.addListener(function(msg) {
        if (msg.greeting == "hello") {
            port.postMessage({ greeting: "hello" });
            console.log('hello');
        }
    });
});
content.js

var port = chrome.runtime.connect({ name: "mycontentscript" });
port.postMessage({greeting: "hello"});
port.onMessage.addListener(function(message) {
    if (message.greeting == "hello") {
        alert('hello');
    }
});