Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Could someone provide me with working examples?

like image 984
user3745387 Avatar asked Apr 04 '16 17:04

user3745387


1 Answers

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
like image 132
Datagrammar Avatar answered Oct 26 '22 13:10

Datagrammar