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

标签 javascript jquery google-chrome-extension

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

有人能给我提供工作示例吗?

最佳答案

解决方案:

内容脚本1

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

内容脚本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) });
});

后台脚本

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

说明:

在内容脚本 1 中,我们通过请求参数中的值 to 指定要调用的选项卡。我们将要发送的数据(在示例中为数字 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

关于javascript - 在两个内容脚本之间传递消息(通过后台),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36409607/

相关文章:

jQuery UI -> 自动完成 -> ON 选择 -> ui 项目未定义

JQuery - 从选定的表行获取值

json - ManifestV3 : "invalid value for web_accessible_resources" or "resources must be listed" errors

javascript - 是否可以实时获取Chrome打包应用程序窗口的位置

javascript - 提取responseJSON对象

javascript - 在 Angular 2 应用程序中注销之前获取最后一个事件 URL

java - 使用 Bouncy CaSTLe 和 Node.js 加密时的不同结果

javascript - 根据 mySQL 数据库中的数据动态更改 svg 图像元素

javascript - jQuery iframe 滚动事件 (IE)

google-chrome-extension - 如果 list v3 中不允许当前选项卡 url,则防止弹出