0

I have this piece of code in my background.js:

chrome.extension.onMessage.addListener( function(request,sender,sendResponse){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        var requests = getTabRequests(tabs[0].id);
                //getTabRequests gets all the information i stored about a tab
        sendResponse( {requests: requests});
    });
 });

What I want it to do, is respond to the popup.js. The chrome.tabs.query makes this impossible for me. I realise this is an asynchronous function, but how to fix it? Or is the only possibility to not send a response, but just another message in the different direction (which means i can't use the callback function in mu popup.js)

Nicky Smits
  • 2,980
  • 4
  • 20
  • 27

1 Answers1

7

Read the documentation of chrome.runtime.onMessage:

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

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        var requests = getTabRequests(tabs[0].id);
        //getTabRequests gets all the information i stored about a tab
        sendResponse({requests: requests});
    });
    return true; // <-- Required if you want to use sendResponse asynchronously!
 });

(chrome.extension.onMessage is deprecated, use chrome.runtime.onMessage instead, the former is an alias of the latter though.)

Rob W
  • 341,306
  • 83
  • 791
  • 678