15

Whenever I try to read from a cookie using the chrome.cookies.get() function I get this error:

TypeError: Cannot read property 'get' of undefined.

I am calling the function in my content.js file, and it will only run on twitter.com(that part works).

Here is my manifest file:

{
  "manifest_version": 2,

  "name": "Twitter-MultiSignin",
  "description": "twiter sign in",
  "version": "1.0",
  "permissions": [ "cookies", "alarms" , "http://*/*", "https://*/*", "storage"],
  "content_scripts": [{
    "matches": ["http://twitter.com/*","https://twitter.com/*"],
    "js": ["jquery.js","content.js"]
  }],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}

Here is my content.js (it always alerts on the twitter page so that works fine):

$(function() {
    alert('got here');
    try{
        chrome.cookies.get({ url: 'https://twitter.com', name: 'auth_token' }, function (cookie){
            alert(cookie.value);
        });
    }catch(err){
        //do nothing
        alert(err);
    }
    try{
        chrome.cookies.get({ url: 'https://twitter.com', name: 'twid' },
        function (cookie) {
            if (cookie) {
              twid_raw = cookie.value;
              twid = twid_raw.split('=')[1]
              alert(twid);
            }
            else{
                alert("not found");
            }
        });
    }catch(err){
        //do nothing
    }
})
Rob W
  • 341,306
  • 83
  • 791
  • 678
parasm
  • 269
  • 1
  • 3
  • 7

5 Answers5

28

Quoting the docs about content scripts:

[Content scripts cannot] Use chrome.* APIs (except for parts of chrome.extension)

So, to use chrome.cookies API, you need to do so from a background page, communicating with the content script if needed.

Xan
  • 74,770
  • 16
  • 179
  • 206
  • So how would I implement that, so that when the user opens Twitter it will get the cookies? – parasm Apr 13 '14 at 01:32
  • 1
    @Oxygen- The API implies that Twitter needs not to be open in order for you to query the cookies. They are tied to a particular URL and not an actual open tab. You need to add a background script, and you can query from there whenever you wish. – Xan Apr 13 '14 at 01:33
  • 1
    oh good point, but I want to read the cookies only on Twitter page load and then be able to scrape some information from the twitter page. Any ideas of how I could implement in a background script? – parasm Apr 13 '14 at 01:36
  • 1
    @Oxygen- You can have both. Cookie-related stuff in the background, content script that loads in Twitter and signals to the background with `sendMessage` that user navigated to it. – Xan Apr 13 '14 at 01:37
  • 1
    What is a "background script"? – Yan Yang Dec 25 '21 at 20:40
  • @YanYang Part of the extension architecture. See https://developer.chrome.com/docs/extensions/mv3/architecture-overview/ Used to be HTML pages with scripts that would run in the background, then (with MV2) became just background scripts, then slowly became event scripts, and with MV3 became service worker scripts. Generally, consider "background script" and "event script" mostly equivalent when reading older Q&A, though of course there are some differences. – Xan Dec 27 '21 at 01:49
4

In case someone skipped this, be sure to add "cookies" to permissions.

jbodily
  • 3,613
  • 2
  • 20
  • 21
0

As per jbodily answer, the missing piece was adding

"permissions": ["activeTab", "cookies"],

To the manifest

Computer's Guy
  • 5,122
  • 8
  • 54
  • 74
0

Beside, "permissions" as specified above, the 'host_permissions' must be inlcuded like:

 ...,
host_permissions: ["https://google.com", "http://localhost"],
....
Dat TT
  • 2,850
  • 2
  • 16
  • 18
0

I'm answering this as a canonical, as "manifest_version": 2, is now outdated.

Here's a simple extension that shows getting cookies from the content, background and popup scripts.

manifest.json:

{
  "manifest_version": 3,
  "name": "Show cookie",
  "version": "1.0.0",
  "description": "Extension to show cookies",
  "author": "g",
  "action": {
    "default_popup": "popup.html",
    "default_title": "Show cookies"
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "cookies",
    "scripting",
    "tabs"
  ],
  "content_scripts": [
    {
      "run_at": "document_start",
      "matches": [
        "http://*/*",
        "https://*/*",
        "<all_urls>"
      ],
      "js": [
        "content.js"
      ],
      "css": [
        "content.style.css"
      ]
    }
  ],
  "host_permissions": [
    "https://*/*"
  ]
}

background.js:

// visible in the extension's devtools console
console.log("background:", chrome.cookies);

content.js:

document.addEventListener("DOMContentLoaded", event => {

  // visible in the webpage's devtools console
  console.log("content script:", document.cookie);

  // visible in the webpage's DOM
  const p = document.createElement("p");
  document.body.prepend(p);
  p.classList.add("cookie");
  p.textContent = document.cookie;
});

popup.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Show cookie extension</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <h3>Cookie</h3>
  <div>loading...</div>
  <script src="popup.js"></script>
</body>
</html>

popup.js:

// https://stackoverflow.com/a/46870005/6243352
async function getCookie(tabId) {
  const [{result}] = await chrome.scripting.executeScript({
    func: () => document.cookie,
    args: [],
    target: {
      tabId: tabId ??
        (await chrome.tabs.query({active: true, currentWindow: true}))[0].id
    },
    world: "MAIN",
  });
  return result;
}

(async () => {
  const cookie = await getCookie();

  // visible in the extension's devtools console
  console.log("popup:", cookie);

  // visible in the extension's DOM
  document.querySelector("div").textContent = cookie;
})();
ggorlen
  • 44,755
  • 7
  • 76
  • 106