清单摘录:
"permissions": [
"tabs",
"cookies",
"*://*/*"
]
我在Popup.js上尝试的代码(不起作用):
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return unescape(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("TestCookie");
if (myCookie == null) {
document.write("<p>unable to load</p>");
throw "stop execution";
}
else {
document.write("<p>loaded</p>");
// do cookie exists stuff
}
}
我认为chrome扩展不支持完整的java,尽管我不确定。我怎么能处理这种情况呢?
答案 0 :(得分:0)
根据您的问题,您不清楚想要获得哪些Cookie。如果您在扩展程序中设置了Cookie,则可以document.cookie
访问它,但这不是在扩展程序中保存持久信息的正确方法,因为有更好的内容,例如localStorage
或chrome.storage
。但是如果您需要在扩展中获取网站cookie,最好的方法是这样的:
chrome.cookies.get({ url: 'http://example.com', name: 'somename' },
function (cookie) {
if (cookie) {
console.log(cookie.value);
}
else {
console.log('Can\'t get cookie! Check the name!');
}
});
不要忘记在manifest中包含权限:
"permissions": [
"cookies",
"*://*.example.com/*"
]