What exactly do you mean by "all cookies related to current tab"?
Any resource loaded over the network could be associated with a cookie. If you just want to get the cookies for all frames within the tab, then use the chrome.webNavigation.getAllFrames
method to get a list of URLs associated with a tab. Here's a very naive method of getting all cookies.
chrome.tabs.query({
currentWindow: true,
active: true
}, function(tabs) {
chrome.webNavigation.getAllFrames({
tabId: tabs[0].id
}, function(details) {
// Get unique list of URLs
var urls = details.reduce(function(urls, frame) {
if (urls.indexOf(frame.url) === -1)
urls.push(frame.url);
return urls;
}, []);
// Get all cookies
var index = 0;
var cookies = [];
urls.forEach(function(url) {
chrome.cookies.getAll({
url: url
}, function(additionalCookies) {
cookies = cookies.concat(additionalCookies);
if (++index === urls.length) {
// Collected all cookies!
// TODO: Use cookies.
// Note: The array may contain duplicate cookies!
}
}); // chrome.cookies.getAll
}); // urls.forEach
}); // chrome.webNavigation.getAllFrames
}); // chrome.tabs.query
The previous method is naive, because the resulting array of cookies might contain duplicate entries (e.g. if the page contains http://example.com
and http://example.com/index.htm
, then you'll get two entries for a cookie on .example.com
).
There are many ways to filter duplicates in a JavaScript array, you can see some methods in this question.
If you want to literally get all cookies associated with a tab, then you need to collect them using the chrome.webRequest
API. Use the webRequest
events to detect network requests and the Cookie
request header and Set-Cookie
and Set-Cookie2
response headers. You have to manually parse the cookie though.
If you want to quickly see all cookies associated with a tab (frames only, like the first method), you can also open the developer tools and look at Resources -> Cookies).
(image source: https://developers.google.com/chrome-developer-tools/docs/resources)