Chrome扩展api;t检查cookie是否存在

Chrome extensions api doesn't check if cookie exists

本文关键字:cookie 是否 存在 检查 扩展 api Chrome      更新时间:2023-09-26

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

查看文档(此处)如果没有cookie,cookie就是null,因此cookie.value应该在后台页面中抛出一个错误,如下所示:Cannot read property 'value' of null。也许可以尝试在getCookies函数中测试null结果,而不是在消息响应中测试。