Tal
Tal

Reputation: 181

Accessing cookies via Chrome extension

I want to write a Chrome extension that would display something on some pages, depending on the value of a cookie that was set by my website. However, my extension simply refuses to acknowledge the existence of the chrome.cookies object (yes, I included "cookies" in the permissions list). I've been testing this by putting the following code in the content script:

$(document).ready(function() {
    console.log (chrome.cookies);
});

It always prints "undefined", and I have no idea why. Is there some usage limitation I should be aware of, or some other necessary details I've missed?

Upvotes: 2

Views: 331

Answers (1)

Tal
Tal

Reputation: 181

Eventually I figured it out...

In the content script:

chrome.extension.sendRequest("getID", function(response) {
    // do something with the id
});

In the background script:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request == 'getID') {
        chrome.cookies.getAll ({domain: 'whatever', name: 'id'}, function (cookies) {
            sendResponse (cookies[0].value);
        });
    }
});

Upvotes: 2

Related Questions