I am trying to get a cookie specifically from a domain using this code:
JavaScript
x
15
15
1
<script language="javascript" type="text/javascript">
2
3
var ID;
4
5
function getCookies(domain, name) {
6
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
7
ID = cookie.value;
8
});
9
}
10
11
getCookies("http://www.example.com", "id")
12
alert(ID);
13
14
</script>
15
The problem is that the alert always says undefined. However, if I change
JavaScript
1
2
1
ID = cookie.value;
2
to
JavaScript
1
2
1
alert(cookie.value);
2
it works properly. How do I save the value to use later?
Update: It appears that if I call alert(ID) from the chrome console after the script runs, it works. How can I set my code to wait until chrome.cookies.get finishes running?
Advertisement
Answer
Almost all Chrome API calls are asynchronous, so you need to use callbacks to run code in order:
JavaScript
1
13
13
1
function getCookies(domain, name, callback) {
2
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
3
if(callback) {
4
callback(cookie.value);
5
}
6
});
7
}
8
9
//usage:
10
getCookies("http://www.example.com", "id", function(id) {
11
alert(id);
12
});
13