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:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With