简体   繁体   中英

Returning pass data from Background.html to popup.html

I've passed data from the background to the popup fine. However, if I return response.reply I get undefined but if I print it out, its not undefined. It's as I expected it to be. How do I return this?

popup.html

function getURL(action){
    chrome.extension.sendRequest(
            {
                req: "geturl",
                act: action
            },
                function(response)
                {
                    return response.reply;
                });
            }

background.html

function getURL(action)
{
    var url = cmshttp+cmshooksurl+"?action="+action;
    return url;
}

You can't return a value from asynchronous function. You need to pass the value to the next function instead (callback).

You code should look like this:

function getURL(action, callback){
    chrome.extension.sendRequest(
            {
                req: "geturl",
                act: action
            },
                function(response)
                {
                    callback(response.reply);
                }
    );
}

Usage:

getURL("some_action", function(reply) {
    console.log("reply is:", reply);
});

background.html:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.req == "geturl") {
        sendResponse({reply:"reply from background"});
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM