Chrome Extension Message passing: response not sent

57,219

Solution 1

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.

Solution 2

The accepted answer is correct, I just wanted to add sample code that simplifies this. The problem is that the API (in my view) is not well designed because it forces us developers to know if a particular message will be handled async or not. If you handle many different messages this becomes an impossible task because you never know if deep down some function a passed-in sendResponse will be called async or not. Consider this:

chrome.extension.onMessage.addListener(function (request, sender, sendResponseParam) {
if (request.method == "method1") {
    handleMethod1(sendResponse);
}

How can I know if deep down handleMethod1 the call will be async or not? How can someone that modifies handleMethod1 knows that it will break a caller by introducing something async?

My solution is this:

chrome.extension.onMessage.addListener(function (request, sender, sendResponseParam) {

    var responseStatus = { bCalled: false };

    function sendResponse(obj) {  //dummy wrapper to deal with exceptions and detect async
        try {
            sendResponseParam(obj);
        } catch (e) {
            //error handling
        }
        responseStatus.bCalled= true;
    }

    if (request.method == "method1") {
        handleMethod1(sendResponse);
    }
    else if (request.method == "method2") {
        handleMethod2(sendResponse);
    }
    ...

    if (!responseStatus.bCalled) { //if its set, the call wasn't async, else it is.
        return true;
    }

});

This automatically handles the return value, regardless of how you choose to handle the message. Note that this assumes that you never forget to call the response function. Also note that chromium could have automated this for us, I don't see why they didn't.

Solution 3

You can use my library https://github.com/lawlietmester/webextension to make this work in both Chrome and FF with Firefox way without callbacks.

Your code will look like:

Browser.runtime.onMessage.addListener( request => new Promise( resolve => {
    if( !request || typeof request !== 'object' || request.type !== "getUrls" ) return;

    $.ajax({
        'url': "http://localhost:3000/urls",
        'method': 'GET'
    }).then( urls => { resolve({ urls }); });
}) );
Share:
57,219

Related videos on Youtube

Abid
Author by

Abid

Freelance Ruby/Rails/Javascript/React/Angular Developer

Updated on May 21, 2020

Comments

  • Abid
    Abid almost 4 years

    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.

    • TrickiDicki
      TrickiDicki over 6 years
      Storing a reference to the sendResponse parameter is critical. Without it, the response object goes out of scope and cannot be called. Thanks for the code which hinted me towards fixing my problem!
    • Enrique
      Enrique over 5 years
      maybe another solution is to wrap everything inside an async function with Promise and call await for the async methods?
  • Zig Mandel
    Zig Mandel about 10 years
    this is correct, I added a way to automate this in my answer
  • rsanchez
    rsanchez about 10 years
    One issue is that sometimes you will not want to call the response function, and in those cases you should return false. If you don't, you are preventing Chrome from freeing up resources associated to the message.
  • Zig Mandel
    Zig Mandel about 10 years
    yes, thats why I said to not forget calling the callback. That special case you menion can be handled by having a convention that the handler (handleMethod1 etc) return false to indicate the "no response" case (though Id rather just always make a response, even an empty one). This way the maintainability problem is only localized to those special "no return" cases.
  • Rob W
    Rob W over 9 years
    Don't re-invent the wheel. The deprecated chrome.extension.onRequest / chrome.exension.sendRequest methods behaves exactly as you describe. These methods are deprecated because it turns out that many extension developers did NOT close the message port. The current API (requiring return true) is a better design, because failing hard is better than leaking silently.
  • funforums
    funforums over 9 years
    +1 for this. It has saved me after wasting 2 days trying to debug this issue. I can't believe that this is not mentioned at all in the message passing guide at: developer.chrome.com/extensions/messaging
  • Zig Mandel
    Zig Mandel over 8 years
    @RobW but whats the issue then? my answer prevents the dev from forgetting to return true.
  • Rob W
    Rob W over 8 years
    @ZigMandel If you want to send a response, just use return true;. It does not prevent the port from being cleaned-up if the call is sync, while async calls are still being processed correctly. The code in this answer introduces unnecessary complexity for no apparent benefit.
  • Zig Mandel
    Zig Mandel over 8 years
    @RobW if it returns true always, seems to me it would keep the port open if the response was already sent (not async, from one of the handlers). why my code does is keep track if a handler already did a (non async) call thus it wont return true in that case. the nice part is i dont have to know which handler is async or not.
  • Rob W
    Rob W over 8 years
    @ZigMandel My point is, you can safely use return true even if the call is synchronous, because after invoking the response callback, the port is already cleaned up.
  • Zig Mandel
    Zig Mandel over 8 years
    @RobW hmm o could swear I added this codex because my extension was leaking ports. ill re evaluate.
  • Qix - MONICA WAS MISTREATED
    Qix - MONICA WAS MISTREATED over 8 years
    I've apparently had this issue before; came back to realize I had already upvoted this. This needs to be in bold in big <blink> and <marquee> tags somewhere on the page.
  • Rob W
    Rob W almost 8 years
    @funforums FYI, this behavior is now documented in the messaging documentation (the difference is here: codereview.chromium.org/1874133002/patch/80001/90002).
  • michaelsnowden
    michaelsnowden almost 8 years
    I swear this is the most unintuitive API I've ever used.
  • Ravi Roshan
    Ravi Roshan about 7 years
    I was breaking my head for almost 4 hours i.e. was able to return directly from Background to Popup BUT NOT from Content to Background to Popup. Tried all possible way, passing this, promise etc, but nothing worked out. Seriously , "I swear this is the most unintuitive API I've ever used."
  • ow3n
    ow3n over 6 years
    Adding my query so Google will index this because I know I'll need it again: "chrome extension send async response from background to contentscript"
  • ferbs
    ferbs about 5 years
    For the next person to hit such messaging problems, take a look at @wranggle/rpc. (Author here.) It helps different windows interact.
  • CuongDC
    CuongDC almost 5 years
    saved my life T_T
  • Diego Fortes
    Diego Fortes about 2 years
    Unfortunately this doesn't seem to work with async/await...