Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension get all tab cookies

Trying to get all cookies from the page, using chrome extension.

For example the page os https://ya.ru.

Here is my code:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var domain = getDomain(tabs[0].url);

    chrome.cookies.getAll({
        domain: domain
    }, function(cookies) {
        console.log(cookies);
    });

});

This code will return all cookies (8) for domain ya.ru. But the problem is when I'm opening the browser console I see cookies not only for ya.ru domain:

enter image description here

Same situation is on google and other sites. So I'm having multiple domain cookies on one page. How to get ALL cookies on the page?

Thank for your time.

like image 319
KaronatoR Avatar asked Sep 01 '25 02:09

KaronatoR


1 Answers

Devtools shows cookies for all resource URLs requested by the page (source code) so we can do the same by accessing Performance API in the content script code that we'll execute in the page:

chrome.tabs.executeScript({
  code: 'performance.getEntriesByType("resource").map(e => e.name)',
}, data => {
  if (chrome.runtime.lastError || !data || !data[0]) return;
  const urls = data[0].map(url => url.split(/[#?]/)[0]);
  const uniqueUrls = [...new Set(urls).values()].filter(Boolean);
  Promise.all(
    uniqueUrls.map(url =>
      new Promise(resolve => {
        chrome.cookies.getAll({url}, resolve);
      })
    )
  ).then(results => {
    // convert the array of arrays into a deduplicated flat array of cookies
    const cookies = [
      ...new Map(
        [].concat(...results)
          .map(c => [JSON.stringify(c), c])
      ).values()
    ];

    // do something with the cookies here
    console.log(uniqueUrls, cookies);
  });
});

Important notes:

  • Your manifest.json should have "<all_urls>" in "permissions" or an explicit list of URL match patterns that will allow the corresponding results in chrome.cookies.getAll.

  • Cookie deduplication code above may be slow when there are thousands of cookies.

  • We're reading cookies for an URL, not domain, because it's the only reliable way to get an encompassing cookie (sstatic.net) for something like i.sstatic.net

like image 131
wOxxOm Avatar answered Sep 03 '25 00:09

wOxxOm