如何检查cookie是否存在?

IT技术 javascript html cookies
2021-01-31 13:16:46

检查 cookie 是否存在的好方法是什么?

条件:

Cookie 存在,如果

cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;

如果 Cookie 不存在

cookie=;
//or
<blank>
6个回答

您可以使用您想要的 cookie 的名称调用函数 getCookie,然后检查它是否为 = null。

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;
        }
    }
    // because unescape has been deprecated, replaced with decodeURI
    //return unescape(dc.substring(begin + prefix.length, end));
    return decodeURI(dc.substring(begin + prefix.length, end));
} 

function doSomething() {
    var myCookie = getCookie("MyCookie");

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
    }
    else {
        // do cookie exists stuff
    }
}
既然unescape已弃用,使用decodeURIComponent代替有什么区别吗?
2021-03-14 13:16:46
@the_nuts,不错的收获。我不知道这个。根据 w3cschools 的 decodeURI() 或 decodeURIComponent 可以用来代替 unescape。选择使用哪个可能取决于存储的内容,我选择了 decodeURI 因为我不希望在 cookie 中编码分隔符。完整参考:w3schools.com/jsref/jsref_decodeuri.asp
2021-03-20 13:16:46
function doSomething($name) { var myCookie = getCookie($name);
2021-03-23 13:16:46
这不适用于第一个 cookie,因为未设置变量 end
2021-03-25 13:16:46
这是为什么 w3schools 不是可靠来源以及为什么您不应该从中复制/粘贴答案的完美示例。你会避免使用 == 和 != 这在 js 中是众所周知的。
2021-03-26 13:16:46

我制作了一个替代的非 jQuery 版本:

document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)

它只测试 cookie 的存在。更复杂的版本也可以返回 cookie 值:

value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]

将您的 cookie 名称替换为MyCookie.

document.cookie 返回以空格分隔的 cookie,即: cookie1= ;cookie1=345534;
2021-03-15 13:16:46
@BogdanM。: 第一个 cookie 没有空格!/[ ]{0,1}/ 见我上面的评论
2021-03-23 13:16:46
美妙的清洁解决方案!这些天人们获取插件的速度太快了……太多的开销。这是一个非常好的解决方案!
2021-03-28 13:16:46
这不起作用。正则表达式缺少一个空格。应该是document.cookie.match(/^(.*;)?MyCookie=[^;]+(.*)?$/),注意?后面的空格。
2021-03-28 13:16:46
如果要使用变量: new RegExp("^(?:.*;)?\\s*" + cookieName + "\\s*=\\s*([^;]+)(?:. *)?$")
2021-04-01 13:16:46
document.cookie.indexOf('cookie_name=');

-1如果该 cookie 不存在,它将返回

ps 唯一的缺点是(如评论中所述)如果设置了具有此类名称的 cookie,则会出错: any_prefix_cookie_name

来源

@hajamie 我认为使用document.cookie.indexOf('cookie_name=') == 0;可以解决这个问题。仅当 cookie 以提到的文本开头时才为真,否则为假。
2021-03-15 13:16:46
@Lasse,仅当这是您拥有的唯一 cookie(或者它是第一个)时。 document.cookie包含所有 cookie 的分号分隔列表。
2021-04-03 13:16:46
这也匹配名称中带有字符串的任何 cookie。例如,该示例返回除-1ifcookie_name_whatever设置之外的其他内容(即使 cookie_name 未设置)。另一个答案中的正则表达式版本解决了这个问题。
2021-04-06 13:16:46
虽然不是 100% 准确,但在大多数情况下这是一个足够好的解决方案。感谢这一点 - 我觉得使用它比使用大函数或来自其他解决方案的复杂正则表达式更舒服。
2021-04-11 13:16:46

注意力!选择的答案包含一个错误(Jac's answer)

如果您有多个 cookie(很可能..)并且您正在检索的 cookie 是列表中的第一个,它不会设置变量“end”,因此它将返回“cookieName”之后的整个字符串=" 在 document.cookie 字符串中!

这是该功能的修订版:

function getCookie( name ) {
    var dc,
        prefix,
        begin,
        end;
    
    dc = document.cookie;
    prefix = name + "=";
    begin = dc.indexOf("; " + prefix);
    end = dc.length; // default to end of the string

    // found, and not in first position
    if (begin !== -1) {
        // exclude the "; "
        begin += 2;
    } else {
        //see if cookie is in first position
        begin = dc.indexOf(prefix);
        // not found at all or found as a portion of another cookie name
        if (begin === -1 || begin !== 0 ) return null;
    } 

    // if we find a ";" somewhere after the prefix position then "end" is that position,
    // otherwise it defaults to the end of the string
    if (dc.indexOf(";", begin) !== -1) {
        end = dc.indexOf(";", begin);
    }

    return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, ''); 
}
replace(/"/g, '') 有问题;它给了我语法错误
2021-03-16 13:16:46
只设置一个 cookie,您的函数返回“cookieName=”。:-/
2021-03-30 13:16:46
它对我有用,但最好避开正则表达式中的引号。我已经编辑了答案。现在也应该为你工作!
2021-04-05 13:16:46
@Jeppe 我已经修改了代码以在只有一个 cookie 时工作。我实际上借此机会重构了整个函数并进行了整理,并添加了一些注释。;)
2021-04-11 13:16:46

这是一个老问题,但这是我使用的方法......

function getCookie(name) {
    var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)')); 
    return match ? match[1] : null;
}

这将null在 cookie 不存在或不包含请求的名称时返回。
否则,返回(请求名称的)值。

没有value的 cookie 永远不应该存在——因为,平心而论,那有什么意义呢?😄
如果不再需要它,最好一起摆脱它。

function deleteCookie(name) {
    document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
这是列表中最好的方法。
2021-03-14 13:16:46
有一个没有value的 cookie 有一个完全正当的理由,那就是表明某物的存在。它将像布尔值一样使用:cookie 存在 => 真,cookie 不存在 => 假
2021-03-18 13:16:46
为什么像这样的功能不是为我们内置的?26.3 年前的 Netscape 0.9b 有 cookie——尽管所有 ECMA 版本都发布了,但在 2.5 年代以来,获取和设置它们似乎没有得到有意义的改进。
2021-04-07 13:16:46
您可以getCookie通过return match && match[1];As this will return nullwhenmatch不是“positive”条件来进一步简化该函数
2021-04-12 13:16:46