0

I am trying to get the response from sendResponse to chrome.runtime.sendMessage, but its always showing undefined, below is my code:

chrome.runtime.sendMessage(JSON.stringify(contact), function(response) {
    console.log('Response: ', response); // This is showing undefined
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
   contact.addContact(request, function() {
      sendResponse({success: 'true'});
   });
});

So when I pass sendResponse({success: true}) that should be received in callback on chrome.runtime.sendMessage but instead of that its showing undefined.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dheeraj Agrawal
  • 2,347
  • 11
  • 46
  • 63

1 Answers1

2

The issue is probably caused by contact.addContact being asynchronous. This means that the listener ends before sendResponse is called. Returning true from the listener like this should fix it:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
   contact.addContact(request, function() {
      sendResponse({success: 'true'});
   });
   return true;
});

From the documentation of chrome.runtime.onMessage:

sendResponse:

Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one onMessage listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

Petr Srníček
  • 2,296
  • 10
  • 22