开发者

Returning pass data from Background.html to popup.html

开发者 https://www.devze.com 2023-02-12 09:16 出处:网络
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 thi

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.repl开发者_运维知识库y;
                });
            }

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"});
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消