双向通信在Chrome扩展程序中返回错误

Exc*_*ion 10 google-chrome-extension

我想之间发送消息contentscript,并background script像下面

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;       
    });
 }
Run Code Online (Sandbox Code Playgroud)

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;
   }
 });
Run Code Online (Sandbox Code Playgroud)

错误
无法发送响应:如果要在侦听器返回后发送响应,则chrome.runtime.onMessage侦听器必须返回true

我该如何解决这个问题.

fun*_*err 21

这应该解决它:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    ...
    return true; //Important
});
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你忘了在第二个添加回报case.