开发者

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

开发者 https://www.devze.com 2023-01-13 12:03 出处:网络
I\'m having trouble communicating with multiple content scripts from my background page. My background page has code like:

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.fromCor开发者_开发百科rectScript) {
    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


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


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 (request, sender, sendResponse) {
  if (request.fromCorrectScript) {
    DoMoreStuff();
  }
}); 

And in scripts:

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

This shouldn't choke.

0

精彩评论

暂无评论...
验证码 换一张
取 消