我正在尝试编写一个适用于 YouTube 的 chrome 扩展程序,并且需要访问 YouTube 的一些 cookie 信息。我似乎无法让我的分机看到任何 cookie。 (尽管我可以在 Chrome 的“检查元素”开发人员部分的资源下看到它们)。
我很确定我已经在 list 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"
}
}
我的 list 调用了 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没有运气。
最佳答案
对于 future 的用户: youtube.com 使用“.youtube.com”作为 cookie 域,以允许该站点在所有 youtube 子域之间共享 cookie,因此在您的示例中,您应该使用不带“www”子域的域名,例如:
chrome.cookies.getAll({domain: "youtube.com"}, function(cookies) {
//...
});
你可以使用默认的 chrome 开发者工具清楚地看到 cookies 域
关于javascript - 在 Chrome 扩展程序中访问 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21199965/