[英]Message passing between two content scripts (through background)
I have two content scripts running in the same page and I need the two to communicate between them via message passing. 我有两个内容脚本在同一页面中运行,我需要两个通过消息传递在它们之间进行通信。 Content script 1 requires data from content script 2 so content script 2 must send a response which ultimate arrives at content script 1. I am aware that they have to passage messages through the background script but I can't get it to work. 内容脚本1需要来自内容脚本2的数据,因此内容脚本2必须发送最终到达内容脚本1的响应。我知道他们必须通过后台脚本传递消息但我无法使其工作。
Could someone provide me with working examples? 有人能为我提供工作实例吗?
var theTabYouWantToCall = 3;
chrome.runtime.sendMessage({ to: theTabYouWantToCall, data: 123 }, function(response) {
console.log("cs1: 123 + 456 = " + response.data);
});
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);
});
});
In content script 1 we specify the tab which we want to call by the value to
in the request parameter. 在内容脚本1,我们指定我们想要的值来调用标签to
在请求参数。 And we put the data we want to send (in the example the number 123
) into the parameter data
. 我们将要发送的数据(在示例中为数字123
)放入参数data
。 And submit it to the background script. 并将其提交给后台脚本。 There, we forward the request to the specified tab and whait for the response of content script 2. When it arrives, we forward it to the callback function sendResponse
. 在那里,我们将请求转发到指定的选项卡,然后查看内容脚本2的响应。当它到达时,我们将它转发给回调函数sendResponse
。 Content script 1 now prints out the result. 内容脚本1现在打印出结果。
What the console of your background script should look like: 后台脚本的控制台应该是什么样子:
[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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.