32

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

document.cookie.length

always returns - 0.

1
  • 10
    do you want to steal cookies?
    – Peter
    Commented Sep 20, 2009 at 14:02

4 Answers 4

51

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/*"
]
1
  • 20
    This worked for me. It is worth mentioning that you need to put this code on the background script. Commented Feb 4, 2015 at 17:48
34

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 :)

3
  • 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
    Commented Dec 22, 2009 at 5:12
  • it gives error: cannot load javascript cookie_handler.js for content_scripts Commented Apr 6, 2012 at 13:22
  • 4
    @MuhammadAdeelZahid You need to write your cookie handler script there :P Commented Feb 1, 2013 at 7: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.

-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.

1
  • 1
    Now we should use chrome.storage.local. Anyway it's an 5-years-ago anwser. Commented Apr 4, 2014 at 5:50