Search code examples
google-chrome-extensionmessage-passing

How should a chrome extension background page communicate with multiple content scripts?


I'm having trouble communicating with multiple content scripts from my background page. My background page has code like:

chrome.tabs.sendRequest(tabId, { targetScript:"content1" }, function (resp) {
  if (resp.fromCorrectScript) {
    DoMoreStuff();
  }
});

and I have content scripts like:

// content1.js
chrome.extension.onRequest.addListener(function (sender, request, sendResponse) {
  if (request.targetScript === "content1") {
    sendResponse({ fromCorrectScript:true });
  } else {
    sendResponse({});
  }
}); 

and

// content2.js
chrome.extension.onRequest.addListener(function (sender, request, sendResponse) {
  if (request.targetScript === "content2") {
    sendResponse({ fromCorrectScript:true });
  } else {
    sendResponse({});
  }
});

My understanding is that my callback in the background page should be called twice, once from each content script. It looks like it's only called twice sometimes, and pretty much only when I have a breakpoint at the if clause. Am I doing something wrong here?

Thanks,

-Greg


Solution

  • Well, it looks like it works correctly as long as I ensure that only one content script responds to the message. So my content script code should be more like:

    // content1.js
    chrome.extension.onRequest.addListener(function (sender, request, sendResponse) {
      if (request.targetScript === "content1") {
        sendResponse({ fromCorrectScript:true });
      }
    });
    

    and

    // content2.js
    chrome.extension.onRequest.addListener(function (sender, request, sendResponse) {
      if (request.targetScript === "content2") {
        sendResponse({ fromCorrectScript:true });
      }
    });