Chrome Cookie API isn't letting me use returned values

后端 未结 1 1591
鱼传尺愫
鱼传尺愫 2021-01-13 15:23

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 l

相关标签:
1条回答
  • 2021-01-13 15:40

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

    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
    });
    
    0 讨论(0)
提交回复
热议问题