双向沟通在Chrome扩展中返回错误 [英] Two way communication is returning error in Chrome Extension
本文介绍了双向沟通在Chrome扩展中返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在 contentscript
和后台脚本
之间发送消息,如下所示
I am trying to send messages between contentscript
and background script
like below
ContentScript.js
chrome.extension.sendMessage({ type : "some" }, function(response) {
anotherFunction( response.data );
return true;
});
function anotherFunction(data){
// Some code here
chrome.extension.sendMessage({ type : "someOther" }, function(response) {
console.log( response.data ); // Failed to get Response
return true;
});
}
Background.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
switch(request.type){
case "some":
sendResponse({ data : "Some Response" });
return true;
break;
case "someOther":
// Here I am getting an error. Error is given below
sendResponse({ data : "Some Response" });
break;
}
});
错误
无法发送回应:如果你想在侦听器返回后发送响应,chrome.runtime.onMessage监听器必须返回true。
Error
Could not send response: The chrome.runtime.onMessage listener must return true if you want to send a response after the listener returns
如何解决这个问题?
推荐答案
这应该解决它:
This should fix it:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
...
return true; //Important
});
在你的情况下,你忘记在第二个 code>。
In your case you forgot to add the return in the second case
.
这篇关于双向沟通在Chrome扩展中返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文