javascriptgoogle-chromegoogle-chrome-extensiongoogle-chrome-app

Chrome Extension Message passing: response not sent


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.


Solution

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

    If you want to asynchronously use sendResponse(), add return true; to the onMessage event handler.

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

    Note this isn't mentioned on other documentation (for example the onMessage documentation) so it's possible developers miss this.