两个内容脚本之间传递的消息(通过后台)

use*_*387 4 javascript jquery google-chrome-extension

我有两个内容脚本在同一页面中运行,我需要两个通过消息传递在它们之间进行通信.内容脚本1需要来自内容脚本2的数据,因此内容脚本2必须发送最终到达内容脚本1的响应.我知道他们必须通过后台脚本传递消息但我无法使其工作.

有人能为我提供工作实例吗?

小智 7

解:

内容脚本1

var theTabYouWantToCall = 3;
chrome.runtime.sendMessage({ to: theTabYouWantToCall, data: 123 }, function(response) {
    console.log("cs1: 123 + 456 = " + response.data);
});
Run Code Online (Sandbox Code Playgroud)

内容脚本2

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("cs2: recieved " + request.data + " from tab " + sender.tab.id);
    sendResponse({ data: (request.data + 456) });
});
Run Code Online (Sandbox Code Playgroud)

背景脚本

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("bgs: forwarded " + request.data + " to the tab " + request.to);
    chrome.tabs.sendMessage(request.to, request.data, function(response) {
        console.log("bgs: forwarded " + response.data + " to the caller " + sender.tab.id);
        sendResponse(response);
    });
});
Run Code Online (Sandbox Code Playgroud)

说明:

在内容脚本1中,我们通过torequest参数中的值指定要调用的选项卡.我们将要发送的数据(在示例中为数字123)放入参数中data.并将其提交给后台脚本.在那里,我们将请求转发到指定的选项卡,然后查看内容脚本2的响应.当它到达时,我们将它转​​发给回调函数sendResponse.内容脚本1现在打印出结果.

示例结果:

后台脚本的控制台应该是什么样子:

[1] bgs: forwarded 123 to the tab 3
[2] cs2: recieved 123 from tab 5
[3] bgs: forwarded 579 to the caller 5
[4] cs1: 123 + 456 = 579
Run Code Online (Sandbox Code Playgroud)

  • 如果内容脚本 1 不知道其他脚本的选项卡 ID 怎么办?特别是,如果 cs1 位于由 cs2 开放的 `iframe` 中,并且 cs1 必须向 cs2 报告,该怎么办? (3认同)