← Articles

Accessing site cookies from a Chrome extension

If you ever tried to read document.cookie from your Chrome extensions background script you probably discovered that when you console.log() or alert() document.cookie 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’d be half right in thinking that. Access to site cookies isn’t posible from the background script, however 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": ["tabs","http://*/*","https://*/*"]

This is obviously just an example as you now trigger the cookie.js file for every site that you visit. However if you place an alert(document.cookie) in your cookie.js file and visit some random site you’ll see the cookies popup in an alert box. Nice but how do you get that info back to your background script. If you played around or read de documents on http://code.google.com/chrome/extensions 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. 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 fly by in the console. Problem solved.

My example 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

Suggestions, tips or flames? Please leave a comment. You can also hire me

Please share this post:
Thomas Cremers google+facebooktwitterstack overflow