Calling a asynchronous function in a callback [dup

2019-02-21 03:43发布

This question already has an answer here:

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)

1条回答
看我几分像从前
2楼-- · 2019-02-21 03:51

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

查看更多
登录 后发表回答