Chrome Cookie API does not allow return values

I am making a chrome extension that sets a cookie on login. When I try to read a cookie using the chrome.cookies.get() method, the callback can log the results, but I cannot pass it from 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 of different ways to pass the result, but it seems that the object is undefined if it is not called from the callback.

+4
source share
1 answer

The problem is that your callback is called after the main function returns. (Extension APIs are called asynchronous for some reason!) returnVal is undefined because it has not been assigned yet. Try changing your function to accept the 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, you can also change your function to return a delayed one. If you have to handle many asynchronous function calls, deferrals make your life easier. Here is 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 }); 
+4
source

All Articles