Chrome扩展程序API不会检查Cookie是否存在

时间:2016-03-26 15:03:09

标签: javascript google-chrome debugging cookies google-chrome-extension

我尝试使用以下代码检查带有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?我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果没有Cookie,那么查看文档(herecookienull,因此cookie.value应该在您的后台页面中抛出错误,这个:Cannot read property 'value' of null。也许尝试在null函数中测试getCookies结果,而不是在消息响应中进行测试。