Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting cookies in a google chrome extension

I am trying to get a cookie specifically from a domain using this code:

<script language="javascript" type="text/javascript">

var ID;

function getCookies(domain, name) {
    chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
        ID = cookie.value;
    });
}

getCookies("http://www.example.com", "id")
alert(ID);

</script>

The problem is that the alert always says undefined. However, if I change

ID = cookie.value;

to

alert(cookie.value);

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?

like image 416
Franz Payer Avatar asked May 05 '11 03:05

Franz Payer


2 Answers

Almost all Chrome API calls are asynchronous, so you need to use callbacks to run code in order:

function getCookies(domain, name, callback) {
    chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
        if(callback) {
            callback(cookie.value);
        }
    });
}

//usage:
getCookies("http://www.example.com", "id", function(id) {
    alert(id);
});
like image 99
serg Avatar answered Oct 06 '22 22:10

serg


Any code that depends on the result of the call to chrome.cookies.get() will have to be invoked from within the callback. In your example, just wait for the callback to fire before you show the alert:

<script language="JavaScript" type="text/javascript">

    var ID;

    function getCookies(domain, name) 
    {
        chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
            ID = cookie.value;
            showId();
        });
    }

    function showId() {
        alert(ID);
    }

    getCookies("http://www.example.com", "id")        

</script>
like image 26
David Mills Avatar answered Oct 06 '22 21:10

David Mills