Chrome 扩展在 "change site data" 时获取 Cookie

Chrome extension get Cookie when "change site data"

关于从我的 chrome 扩展中获取 Cookie,当 chrome 设置为“在所有站点上”时,它工作得很好。

但是当我在 chrome 扩展程序设置中设置“在 [当前站点] 上”或“当您单击扩展程序时”时,我无法获得任何 cookies..

https://support.google.com/chrome_webstore/answer/2664769?hl=en “让扩展程序读取和更改站点数据”

※ 当我一直打开我要获取cookie的url时,就成功了...

我试图寻找解决方案,但一无所获。

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "desc",
  "permissions": [
    "contextMenus",
    "tabs",
    "cookies"
  ],
  "host_permissions": [ "https://wanna-get-cookie-this-domain.com/*" ],
  "background": { "service_worker": "service_worker.js" },
  "content_scripts": [
     {
       "js": ["scripts/contentscript.js"],
       "matches": ["https://*/*"]
     }
  ],
  "manifest_version": 3
}

service_woeker.js

chrome.contextMenus.create({
  id: "testapp",
  title: "title",
  contexts: ["all"],
  type: "normal"
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
  chrome.windows.create({
    url: `/views/popup.html`,
    type: 'popup',
    focused: true,
    width: 395, height: 230
  });
})

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.type == "getCookie") {
    chrome.cookies.getAll({}, function(cookies) {
      console.log(cookies);
      // "On all sites" works. 
      // "On [current site]" or "When you click the extension" doesn't work 
      // even after I clicked and enabled the extension.
    });
  }

  return true;
});

views/popup.html

<html>
 ...
<script src="/scripts/popup.js"></script>
</html>

scripts/popup.js

// After user clicked, below code
chrome.runtime.sendMessage({type: 'getCookie'}));

谢谢,

这是一个bug:

the cookies API is only checking the host permissions, and not checking tab-specific permissions, since the request isn't associated with a tab.

在修复之前,您将为 manifest.json 中的所有站点添加主机权限:

  "host_permissions": ["<all_urls>"]

请注意,您的内容脚本已经在所有 https 网站上运行(为什么不是所有网站?),这意味着您的扩展已经在后台请求“广泛的主机许可”,因此将相同的模式添加到 host_permissions 不会增加扩展程序的内部权限,允许在 non-content 脚本(如后台脚本)中使用 chrome API 更像是一种装饰性要求。