3

我尝试了以下但不知道如何操作它。

清单.json

  "permissions": [
    "tabs",
    "http://*/*",
    "https://*/*"
  ],
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["cookie.js"]
    }
  ]

cookie.js

console.log(document.cookie);

只是在当前页面 console.log 中显示,而不是在扩展的实际控制台中。

是否可以获取您当前所在站点的 cookie 并将其设置在扩展程序的本地存储中?所以到那时,我可以在任何页面上,并且扩展仍然具有价值。

4

1 回答 1

10

以下骨架有助于实现它;我将所有cookie信息存储在 chrome 扩展本地存储中,如下所示;

示例代码

在此处输入图像描述

清单.json

{
  "name" : "Cookie API Demo",
  "version" : "1",
  "description" : "This is demonstration of Cookie API",
  "permissions": [ "cookies","<all_urls>"],
  "browser_action": {
    "default_icon": "screen.png",
    "default_popup":"popup.html"
  },
  "manifest_version": 2
}

popup.html

<html>
<head>
<script src="popup.js"></script>
</head>
<body>
</body>
</html>

popup.js

function cookieinfo(){
    chrome.cookies.getAll({},function (cookie){
        console.log(cookie.length);
        allCookieInfo = "";
        for(i=0;i<cookie.length;i++){
            console.log(JSON.stringify(cookie[i]));

            allCookieInfo = allCookieInfo + JSON.stringify(cookie[i]);
        }
        localStorage.allCookieInfo = allCookieInfo;
    });
}
window.onload=cookieinfo;

更多API的检查这个

骨架仅适用于当前页面中的 Cookie

如此处所示,您将在当前页面中只有 cookie 信息

在此处输入图像描述

清单.json

{
  "name" : "Cookie API Demo",
  "version" : "1",
  "description" : "This is demonstration of Cookie API",
  "permissions": [ "cookies","<all_urls>","tabs"],
  "browser_action": {
    "default_icon": "screen.png",
    "default_popup":"popup.html"
  },
  "manifest_version": 2
}

popup.html

<html>
<head>
<script src="popup.js"></script>
</head>
<body>
</body>
</html>

popup.js

function cookieinfo(){

     chrome.tabs.query({"status":"complete","windowId":chrome.windows.WINDOW_ID_CURRENT,"active":true}, function(tab){
            console.log(JSON.stringify(tab));
            chrome.cookies.getAll({"url":tab[0].url},function (cookie){
                console.log(cookie.length);
                allCookieInfo = "";
                for(i=0;i<cookie.length;i++){
                    console.log(JSON.stringify(cookie[i]));

                    allCookieInfo = allCookieInfo + JSON.stringify(cookie[i]);
                }
                localStorage.currentCookieInfo = allCookieInfo;
            });
    });

}
window.onload=cookieinfo;
于 2012-11-28T15:04:33.887 回答