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