Two way communication is returning error in Chrome Extension [duplicate]

大兔子大兔子 提交于 2019-12-18 02:46:20

问题


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

Error
Could not send response: The chrome.runtime.onMessage listener must return true if you want to send a response after the listener returns

How can I fix this issue.?


回答1:


This should fix it:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    ...
    return true; //Important
});

In your case you forgot to add the return in the second case.



来源:https://stackoverflow.com/questions/16419563/two-way-communication-is-returning-error-in-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!