【问题标题】:Accessing Cookies in Chrome Extension在 Chrome 扩展程序中访问 Cookie
【发布时间】:2014-02-07 14:43:49
【问题描述】:

我正在尝试编写一个适用于 YouTube 的 chrome 扩展程序,并且需要访问一些 YouTube 的 cookie 信息。我似乎无法让我的扩展程序看到任何 cookie。 (尽管我可以在 Chrome 的“检查元素”开发人员部分的资源下看到它们)。

我很确定我在清单 2 文件中正确设置了权限,因为当我取出“cookies”权限只是为了测试它时,我收到一条错误消息“无法调用方法'getAll'”。我目前的问题是回调函数没有返回任何cookie。

{
"manifest_version": 2,
"name": "YouTube Viewer",
 "description": "This extension is for YouTube videos.",
 "version": "1.7",

 "icons": {
 "128": "ytblack.png"
 },

 "permissions": [
 "cookies",
 "https://www.youtube.com/",
 "http://www.youtube.com/",
 "tabs",
 "storage"
 ],

 "background": {
   "scripts": ["bootstrap.js"],
   "persistent": false
  },

 "page_action": {
 "default_title": "YT View",
 "default_icon": "ytblack.png",
 "default_popup": "popup.html"
 }

}

我的清单调用 bootstrap.js。在 bootstrap.js 中有对另一个文件 ytview.js 的调用,但我不关心这个。其中的代码工作正常。但是在 bootstrap.js 中,当我查看“背景页面”控制台时,我的 cookies.length 返回为 0。 “Cookie 回调正常”的日志。正确触发。但后来它说“cookies.length = 0”。就像我说的,我知道 cookie 存在是因为我可以在资源中看到它们。

chrome.tabs.onUpdated.addListener(function(id, info, tab){

// decide if we're ready to inject content script
if (tab.status !== "complete"){
    console.log("not yet");
    return;
}
if (tab.url.toLowerCase().indexOf("youtube.com/watch") === -1){
    console.log("you are not on a YouTube video");
    return;
}

chrome.cookies.getAll({domain: "www.youtube.com"}, function(cookies) {
console.log('Callback for cookies came in fine.');
console.log('cookies.length=' + cookies.length);        
    for(var i=0; i<cookies.length;i++) {
      console.log('cookie=' + cookies[i].name);
    }
  });
chrome.tabs.executeScript(null, {"file": "ytview.js"});

});

知道为什么没有返回 cookie 吗?也许 .getAll 语句中带有“域”的东西?我尝试了很多组合,例如 www.youtube.com、youtube.com、https://www.youtube.com,但都没有成功。

【问题讨论】:

    标签: javascript google-chrome cookies google-chrome-extension browser-addons


    【解决方案1】:

    对于未来的用户: youtube.com 使用“.youtube.com”作为 cookie 域,以允许该站点在所有 youtube 子域之间共享 cookie,因此在您的示例中,您应该使用不带“www”子域的域名,例如:

    chrome.cookies.getAll({domain: "youtube.com"}, function(cookies) {
      //...
    });
    

    您可以使用默认的 chrome 开发者工具清楚地看到 cookie 域

    【讨论】:

      【解决方案2】:

      我想通了。在我的清单中,我在 www.youtube.com 上请求许可,但我试图阅读的 cookie 只是在没有 www.youtube.com 的 youtube.com 上。将普通的 youtube.com 添加到清单中的权限修复它。

      【讨论】:

        猜你喜欢
        • 2010-11-29
        • 1970-01-01
        • 1970-01-01
        • 2015-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多