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

With a chrome extension, how do I pass a message from background script to content script using a long-lived connection (port)?

本文关键字:脚本 后台 消息 端口 扩展 chrome 何使用 连接 使用      更新时间:2024-06-07

这是我的背景脚本。我可以通过弹出脚本向它发送消息。换句话说,控制台在后台页面中记录"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');
    }
});

我做错了什么?谢谢

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

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');
    }
});

我不知道我的情况是否和你的完全一样,但我也写了一个Chrome扩展,后台页面在其中向客户端发送消息。

在我的内容脚本中,我执行以下操作:

chrome.runtime.sendMessage('requestData', this.updateData.bind(this));

在我的背景脚本中,我有:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    sendResponse({
        messages : inboxMessages,
        userId   : user_id
    });
});

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

this.updateData = function(data) {
    //...
}

希望这对你有帮助!

在后台.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});

行。