Chrome Cookie API不允许我使用返回的值 [英] Chrome Cookie API isn't letting me use returned values

查看:490
本文介绍了Chrome Cookie API不允许我使用返回的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a chrome extension which sets a cookie when users log in. When I attempt to read the cookie using the chrome.cookies.get() method the callback can log the results but I cant pass it out of the callback.

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

我尝试使用两种不同的方式传递结果,除非从回调中调用,否则对象是未定义的。

I tried using a couple different ways of passing the result but it seems like the object is undefined unless it is called from within the callback.

推荐答案

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

The problem is that your callback is called after the main function returns. (The extension APIs are called asynchronous for a reason!) returnVal is undefined because it hasn't been assigned to yet. Try modifying your function to accept a callback argument:

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

如果你不喜欢传递回调,你也可以修改你的函数返回一个延迟。如果你必须处理很多异步函数调用,延迟使你的生活更容易。下面是一个使用jQuery.Deferred的例子:

If you don't like passing callbacks around, you could also modify your function to return a deferred. If you have to handle a lot of asynchronous function calls, deferreds make your life a lot easier. Here's an example using 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
});

这篇关于Chrome Cookie API不允许我使用返回的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆