views:

28

answers:

2

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

A: 

I don't know what's the root of the problem, can only guess that whichever script runs callback first destroys it for the rest.

I can suggest workaround though. You can send requests in both directions, not only from background page to script. So your background page might look like:

chrome.tabs.sendRequest(tabId, { targetScript:"content1" });

chrome.extension.onRequest.addListener(function (sender, request, sendResponse) {
  if (request.fromCorrectScript) {
    DoMoreStuff();
  }
}); 

And in scripts:

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

This shouldn't choke.

serg
In the past I've had my extension choke when the content script didn't call the sendResponse callback. I'll check if that's still the case.
Greg
A: 

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 });
  }
});
Greg

related questions