最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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
发布评论

评论列表(0)

  1. 暂无评论