26

Is there any way to access cookies from Chrome extension? this code

document.cookie.length

always returns - 0.

Dan Herbert
  • 99,428
  • 48
  • 189
  • 219

4 Answers4

43

Currently the best (the simplest) way to get site cookies in an extension is put this code in your background script:

chrome.cookies.get({ url: 'http://example.com', name: 'somename' },
  function (cookie) {
    if (cookie) {
      console.log(cookie.value);
    }
    else {
      console.log('Can\'t get cookie! Check the name!');
    }
});

So now you don't need content script for this but don't forget to include permissions into manifest:

"permissions": [
  "cookies",
  "*://*.example.com/*"
]
Raine Revere
  • 30,985
  • 5
  • 40
  • 52
Konstantin Smolyanin
  • 17,579
  • 12
  • 56
  • 56
33

It's the first time I read something really wrong on this site. Getting actual document cookies from an extension is INDEED possible.

you just need these two things in your manifest:

"content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["cookie_handler.js"]
    }
  ],
  "permissions": [
    "tabs",
    "http://*/*",
    "https://*/*"
  ],

your cookie_handler.js will be executed in the same context of every loader page/frame/iframe. try to put there a single line:

alert(document.cookie);

and you will see :)

Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
Zibri
  • 9,096
  • 3
  • 52
  • 44
  • Does this mean that it is possible to make an extension like Permit Cookies from Firefox? That extension allows the user for each site to Allow always, Allow for session, Block, Remove. Or can such an extension not be made for Chrome? – Louise Dec 22 '09 at 05:12
  • it gives error: `cannot load javascript cookie_handler.js for content_scripts` – Muhammad Adeel Zahid Apr 06 '12 at 13:22
  • 4
    @MuhammadAdeelZahid You need to write your cookie handler script there :P – Prashant Singh Feb 01 '13 at 07:32
3

If you're looking to manipulate cookie information without the user having to visit the site, (useful for something like FireFox's TACO), you're currently out of luck. Looks like Google's working on it though: they recently added a relatively complete cookie handler to the experimental API: chrome.experimental.cookies

Hopefully this will graduate to supported API soon.

Ian Wilkes
  • 681
  • 5
  • 5
-6

Even better, you can use the HTML5 Localstorage:

localStorage.setItem("itemid", "hello" );   // write
value = localStorage.getItem("itemid");     // read

If you really wanted to read the cookies of any site the user is watching, as Dan wrote, it is not possible, as really bad things could be done.

All you can get from a page is the page DOM content.

Omiod
  • 11,285
  • 11
  • 53
  • 59