Monday, January 25, 2010

Accessing site cookies from a Chrome extension

If you tried to play around with this you probably discovered that when you console.log() or alert() document.cookie from the background script in you extension you're greeted with a "false" message. Maybe you even left it at that (probably not as you're reading this) and decided that access is restricted for security reasons.
Well, you would be half right in thinking that. Access to site cookies isn't posible from the background script, how ever it's no problem from a content_script. Consider the following contents_scripts section in you manifest.json file.
"content_scripts": [
"matches": ["http://*/*", "https://*/*"],
"js": ["cookie.js"]
And with that goes a permissions section on the same level in your manifest.json file.
"permissions": [
Now this is obviously just an example as you now trigger the cookie.js file for every site that you visit.
However if you now place an alert(document.cookie) in your cookie.js file and visit some random sites you'll see the cookies popup in an alert box.

Communicating with the background from you content_script
Okay, so this's all nice but how do you get that info back to your background script. If you played around or read de documents on you know that simply calling chrome.extensions.getBackgroundPage() doesn't work, that's because all access to chrome.extension.* is restricted accept for the message api.

So let's try to use that. If you open up the cookie.js file and add the following line.
chrome.extension.sendRequest({cookie: document.cookie});
Now a message is send out plugin wide (in this case) containing the content of document.cookie associated with the label cookie.
Next thing we need to do is listen for that message in our background script. So open up your background.html file and add the following snippet.
function(request, sender, sendResponse) {
Don't forget to reload the plugin, now click on the background.html link underneath your plugin on the Extensions page to open up the inspector and click the console button. Now if you visit a couple of websites you should see the cookie contents go by in the console.

So that's how you do it. My usage of the message API in chrome is very basic, a lot more is available even message sending over different extensions is a possibility. Read more on the subject here


  1. Very helpful, thanks you!

  2. Too bad sendRequest is obsolete.

  3. Too bad sendRequest is obsolete.

    1. This was written in 2010 so I'm not surprised a lot has changed since then

  4. Some days ago i tried to get torrent downloading site cookies. So i was trying with the ways you shared But not succeeded.