Skip to content Skip to sidebar Skip to footer

Calling A Asynchronous Function In A Callback

I have this piece of code in my background.js: chrome.extension.onMessage.addListener( function(request,sender,sendResponse){ chrome.tabs.query({active: true, currentWindow: tr

Solution 1:

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 tabsendResponse({requests: requests});
    });
    returntrue; // <-- 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.)

Post a Comment for "Calling A Asynchronous Function In A Callback"