Chrome 扩展后台页面应该如何与多个内容脚本进行通信?
我在与后台页面的多个内容脚本进行通信时遇到问题。我的后台页面有如下代码:
chrome.tabs.sendRequest(tabId, { targetScript:"content1" }, function (resp) {
if (resp.fromCorrectScript) {
DoMoreStuff();
}
});
我有如下内容脚本:
// content1.js
chrome.extension.onRequest.addListener(function (sender, request, sendResponse) {
if (request.targetScript === "content1") {
sendResponse({ fromCorrectScript:true });
} else {
sendResponse({});
}
});
我的理解是
// content2.js
chrome.extension.onRequest.addListener(function (sender, request, sendResponse) {
if (request.targetScript === "content2") {
sendResponse({ fromCorrectScript:true });
} else {
sendResponse({});
}
});
,我在后台页面中的回调应该被调用两次,每个内容脚本调用一次。看起来有时它只被调用两次,而且几乎只有当我在 if
子句中有断点时才被调用。我在这里做错了什么吗?
谢谢,
-格雷格
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,看起来只要我确保只有一个内容脚本响应该消息,它就可以正常工作。所以我的内容脚本代码应该更像是:
和
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:
and
我不知道问题的根源是什么,只能猜测首先运行回调的脚本会销毁其余的脚本。
不过我可以建议解决方法。您可以双向发送请求,而不仅仅是从后台页面到脚本。所以你的背景页面可能看起来像:
在脚本中:
这不应该令人窒息。
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:
And in scripts:
This shouldn't choke.