2

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

我很确定我已经在manifest 2文件中正确设置了权限,因为当我拿出“cookies”权限来测试它时,我收到一个错误,提示“Can not call method'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语句中带有“domain”的东西?我尝试了很多组合,例如www.youtube.com,youtube.com,https://www.youtube.com,但没有运气。

回答

0

我想通了。在我的清单中,我要求在www.youtube.com上获得许可,但我试图阅读的cookies只是在没有www的情况下在youtube.com上。将纯粹的youtube.com添加到清单中的权限中修复它。

1

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

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

使用默认的Chrome开发者工具,你可以清楚地看到饼干域

enter image description here