我尝试使用以下代码检查带有Chrome扩展名的Cookie
content.js
if (hostName == "google.com") {
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
if (response.farewell == null) {console.log("cookie is null");}
});
}
background.js
function getCookies(domain, name, callback) {
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
if(callback) {
callback(cookie.value);
}
});
}
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.greeting == "hello") {
getCookies("http://www.google.com", "cookie_name", function(id) {
if (id) {
alert("cookie "+id);
sendResponse({farewell: id});
} else {
alert("cookie "+id);
sendResponse({farewell: id});
}
});
return true;
}
});
如果设置了cookie,此代码有效。但是如果没有cookie,就没有警报和响应。 如何检查是否没有cookie?我做错了什么?
答案 0 :(得分:0)
如果没有Cookie,那么查看文档(here)cookie
为null
,因此cookie.value
应该在您的后台页面中抛出错误,这个:Cannot read property 'value' of null
。也许尝试在null
函数中测试getCookies
结果,而不是在消息响应中进行测试。