admin 管理员组文章数量: 1086019
I have two content scripts running in the same page and I need the two to municate 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.
Could someone provide me with working examples?
I have two content scripts running in the same page and I need the two to municate 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.
Could someone provide me with working examples?
Share Improve this question edited Apr 4, 2016 at 18:04 Michał Perłakowski 92.8k30 gold badges163 silver badges187 bronze badges asked Apr 4, 2016 at 17:57 user3745387user3745387 1651 silver badge7 bronze badges1 Answer
Reset to default 10Solution:
content script 1
var theTabYouWantToCall = 3;
chrome.runtime.sendMessage({ to: theTabYouWantToCall, data: 123 }, function(response) {
console.log("cs1: 123 + 456 = " + response.data);
});
content script 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) });
});
background script
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);
});
});
Explanation:
In content script 1 we specify the tab which we want to call by the value to
in the request parameter. And we put the data we want to send (in the example the number 123
) into the parameter 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
.
Content script 1 now prints out the result.
Result of the example:
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
本文标签: javascriptMessage passing between two content scripts (through background)Stack Overflow
版权声明:本文标题:javascript - Message passing between two content scripts (through background) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744058480a2526283.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论