javascript - Message passing between two content scripts (through background) - Stack Overflow

I have two content scripts running in the same page and I need the two to municate between them via mes

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 badges
Add a ment  | 

1 Answer 1

Reset to default 10

Solution:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744058479a4551339.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信