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 diff开发者_如何转开发erent ways of passing the result but it seems like the object is undefined unless it is called from within the callback.
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
});
精彩评论