Chrome Cookie API 不允许我使用返回值

dev*_*ill 4 javascript cookies google-chrome-extension

我正在制作一个 chrome 扩展,它在用户登录时设置一个 cookie。当我尝试使用该chrome.cookies.get()方法读取 cookie 时,回调可以记录结果,但我无法将其从回调中传递出去。

function getCookie (cookieName){
    var returnVal; 
    chrome.cookies.get({
        'url':'https://addictedtogether.com/',
        'name':cookieName
    },
    function(data){
        console.log(data); //log displays returned cookie in a object
        returnVal=data;
    }
    );
    console.log(returnVal);  //log says this is undefined
    return returnVal;
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用几种不同的方式来传递结果,但似乎对象是未定义的,除非它是从回调中调用的。

Na7*_*ter 6

问题是您的回调是主函数返回调用的。(扩展 API 被称为异步是有原因的!)returnVal未定义,因为它尚未分配给。尝试修改您的函数以接受回调参数:

function getCookie (cookieName, callback){
    chrome.cookies.get({
        'url':'https://addictedtogether.com/',
        'name':cookieName
    },
    function(data){
        callback(data);
    });
}

// Use like this:
getCookie("CookieName", function(cookieData){
  // Do something with cookieData
});
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢传递回调,您还可以修改您的函数以返回延迟。如果您必须处理大量异步函数调用,则延迟使您的生活更轻松。下面是一个使用 jQuery.Deferred 的例子:

function getCookie (cookieName){
    var defer = new jQuery.Deferred();
    chrome.cookies.get({
        'url':'https://addictedtogether.com/',
        'name':cookieName
    },
    function(data){
        defer.resolve(data);
    });
    return defer.promise();
}
// Example use:
getCookie("FooBar").done(function(data){
  // Do something with data
});
Run Code Online (Sandbox Code Playgroud)