3

我正在尝试编写一个适用于 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 ,但都没有运气。

4

2 回答 2

2

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

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

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

在此处输入图像描述

于 2016-08-08T06:28:57.753 回答
1

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

于 2014-01-18T07:06:20.193 回答