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