11

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.?

Exception
  • 8,111
  • 22
  • 85
  • 136
  • 2
    Have you tried adding a `return true` in your second `case` like the error message suggests? – apsillers May 07 '13 at 13:00
  • 1
    @apsillers Yes it is working fine. I had to put return true in two places but I had put in only one place.. That was the issue. Thanks for pointing out. Could you please post it as answer so that I can accept it. – Exception May 07 '13 at 13:01

1 Answers1

25

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.

funerr
  • 7,212
  • 14
  • 81
  • 129