Chrome 扩展程序获取所有标签 cookie

Kar*_*toR 3 cookies google-chrome-extension google-chrome-devtools

尝试使用 chrome 扩展从页面获取所有 cookie。

例如页面 os https://ya.ru

这是我的代码:

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);
    });

});
Run Code Online (Sandbox Code Playgroud)

此代码将返回域 ya.ru 的所有 cookie (8)。但问题是当我打开浏览器控制台时,我不仅看到了 ya.ru 域的 cookie:

在此处输入图片说明

谷歌和其他网站也有同样的情况。所以我在一个页面上有多个域 cookie。如何获取页面上的所有 cookie?

感谢您的时间。

wOx*_*xOm 7

Devtools 显示页面(源代码)请求的所有资源 URL 的 cookie,因此我们可以通过访问我们将在页面中执行的内容脚本代码中的Performance API来执行相同的操作:

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

重要笔记:

  • 你的manifest.json应该"<all_urls>""permissions"或URL匹配模式,将允许在chrome.cookies.getAll相应结果的显式列表。

  • 当有数千个 cookie 时,上面的 cookie 重复数据删除代码可能会很慢。

  • 我们正在读取 URL 的 cookie,而不是域,因为这是获取 i.stack.imgur.com 之类的包含 cookie (imgur.com) 的唯一可靠方法