Search code examples
javascriptgoogle-chromegoogle-chrome-extensioncontent-scriptmanifest.json

How to capture a cookie via a Chrome extension


I need to capture a cookie from an especific website and I am trying to do that using a Chrome extension, but I have never created one. I have read a lot of tutorials but I was not able to do that.

I am trying to capture the cookie using a content script, but I receive an error message every time.

This is the code of my manifest, content script and the error...

manifest.json

...
    
"manifest_version": 3,

"permissions": [
    "cookies"
 ],

"content_scripts": [{
    "matches": ["*://google.com/"],
    "js": ["content.js"]
}]

content.js


var ID;

function getCookies(domain, name) {
    chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
        ID = cookie.value;
        showId();
    });
}

function showId() {
    alert(ID);
}

getCookies("https://google.com/", "SSID");  

Error: Uncaught TypeError: Cannot read property 'get' of undefined

How can I fix it?


Solution

  • The documentation for chrome.cookies.get states:

    [...] If host permissions for this URL are not specified in the manifest file, the API call will fail.

    You need to request permissions for all the domains for which you are interested in, which means adding them in the permissions declared in your manifest.json:

    "permissions": [
        "cookies",
        "*://google.com/"
    ],
    

    Secondly, you don't actually need to inject a content script to extract the cookies. You can simply do this in your background page if you want.