将传递数据从Background.html返回到popup.html

时间:2011-02-22 15:25:07

标签: javascript google-chrome-extension

我已将数据从后台传递到弹出窗口。但是,如果我返回response.reply我得到了未定义但是如果我将其打印出来,那么它是未定义的。就像我预期的那样。我该如何归还?

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;
}

1 个答案:

答案 0 :(得分:1)

您无法从异步函数返回值。您需要将值传递给下一个函数(回调)。

您的代码应如下所示:

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

用法:

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