Chrome Extension Message passing: response not sent

Abid picture Abid · Nov 19, 2013 · Viewed 52.7k times · Source

I am trying to pass messages between content script and the extension

Here is what I have in content-script

chrome.runtime.sendMessage({type: "getUrls"}, function(response) {
  console.log(response)
});

And in the background script I have

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.type == "getUrls"){
      getUrls(request, sender, sendResponse)
    }
});

function getUrls(request, sender, sendResponse){
  var resp = sendResponse;
  $.ajax({
    url: "http://localhost:3000/urls",
    method: 'GET',
    success: function(d){
      resp({urls: d})
    }
  });

}

Now if I send the response before the ajax call in the getUrls function, the response is sent successfully, but in the success method of the ajax call when I send the response it doesn't send it, when I go into debugging I can see that the port is null inside the code for sendResponse function.

Answer

rsanchez picture rsanchez · Nov 19, 2013

From the documentation for chrome.runtime.onMessage.addListener:

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

So you just need to add return true; after the call to getUrls to indicate that you'll call the response function asynchronously.