Chrome扩展程序:获取当前页面Cookie并与插件本地存储相同

时间:2012-11-28 14:35:29

标签: javascript cookies google-chrome-extension local-storage

我尝试了以下但不确定如何操纵它。

的manifest.json

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

cookie.js

console.log(document.cookie);

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

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

1 个答案:

答案 0 :(得分:6)

以下Skeleton有助于实现它;我将所有cookie信息存储在Chrome扩展程序本地存储中,如此处所示;

示例代码

enter image description here

<强> 的manifest.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的检查THIS

骨架仅限当前页面中的Cookie

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

enter image description here

<强> 的manifest.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;