我在同一个页面中运行了两个内容脚本,我需要这两个脚本通过消息传递在它们之间进行通信。内容脚本 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/