list 摘录:
"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,尽管我不确定。我该如何应对这种情况?
最佳答案
从您的问题来看,尚不清楚您想要获得什么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!');
}
});
不要忘记将权限包含到 list 中:
"permissions": [
"cookies",
"*://*.example.com/*"
]
关于javascript - 通过 chrome 扩展检查 cookie 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13778966/