如果cookie存在,请检查cookie

con*_*led 68 html javascript cookies

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

条件:

Cookie存在,如果

cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
Run Code Online (Sandbox Code Playgroud)

如果,Cookie不存在

cookie=;
//or
<blank>
Run Code Online (Sandbox Code Playgroud)

jac*_*jac 109

您可以使用所需的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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 由于`unescape`已被弃用,使用`decodeURIComponent`会有什么不同吗? (3认同)
  • @the_nuts,很好听.我不知道这个.根据w3cschools的decodeURI(),或者decodeURIComponent可以用来替换unescape.选择使用哪个可能归结为存储的内容,我选择了decodeURI,因为我不希望在cookie中编码分隔符.完整参考:http://www.w3schools.com/jsref/jsref_decodeuri.asp (3认同)
  • 这不适用于第一个Cookie,因为未设置变量end (2认同)
  • 这是为什么 w3schools 不是可靠来源以及为什么您不应该从中复制/粘贴答案的完美示例。你会避免使用 == 和 != 这在 js 中是众所周知的。 (2认同)

heg*_*mon 72

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

document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)
Run Code Online (Sandbox Code Playgroud)

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

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

将您的cookie名称替换为MyCookie.

  • 精彩的清洁解决方 这些天人们过快地抓住插件......开销太大了.这是一个非常好的解决方案! (9认同)
  • 如果要使用变量: new RegExp("^(?:.*;)?\\s*" + cookieName + "\\s*=\\s*([^;]+)(?:. *)?$") (6认同)
  • 这不起作用.正则表达式缺少一个空间.它应该是document.cookie.match(/^(.*;)?MyCookie = [^;] +(.*)?$ /),注意后面的空格? (3认同)

Hac*_*ell 23

document.cookie.indexOf('cookie_name=');
Run Code Online (Sandbox Code Playgroud)

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

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

(来源)

  • 虽然不是 100% 准确,但在大多数情况下这是一个足够好的解决方案。感谢这一点 - 我觉得使用它比使用大函数或来自其他解决方案的复杂正则表达式更舒服。 (6认同)
  • 这也匹配任何名称中包含字符串的cookie.例如,如果设置了`cookie_name_whatever`,则示例将返回除"-1"以外的内容(即使cookie_name不是).另一个答案中的正则表达式版本解决了这个问题. (3认同)
  • @Lasse,只有当这是你拥有的唯一的cookie(或者它是第一个)时。[document.cookie](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) 包含所有 cookie 的分号分隔列表。 (2认同)

Dus*_*ead 11

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

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

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

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

function deleteCookie(name) {
    document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
Run Code Online (Sandbox Code Playgroud)

  • 这是列表中最好的方法。 (3认同)
  • 拥有一个没有值的 cookie 有一个完全正当的理由,那就是表明某物的存在。它将像布尔值一样使用:cookie 存在 =&gt; true,cookie 不存在 =&gt; false (2认同)
  • 为什么没有为我们内置这样的功能?26.3 年前的 Netscape 0.9b 就有了 cookie - 尽管推出了所有 ECMA 版本,但在 2.5 年来,获取和设置它们似乎并没有得到有意义的改进。 (2认同)
  • 您可以通过“return match &amp;&amp; match[1];”进一步简化“getCookie”函数,因为当“match”不是“正”条件时,这将返回“null”。 (2认同)

Pik*_*kio 9

注意!所选答案包含一个错误(Jac的回答).

如果你有多个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, ''); 
}
Run Code Online (Sandbox Code Playgroud)


HeW*_*cts 6

如果您正在使用jQuery,则可以使用jquery.cookie插件.

获取特定cookie的值如下:

$.cookie('MyCookie'); // Returns the cookie value
Run Code Online (Sandbox Code Playgroud)

  • 这不仅仅是jquery特有的,还需要一个你在答案中没有引用的jquery插件 (7认同)
  • 这也假设OP正在使用jquery-cookie插件.因为我使用的是jquery,所以它让我有点循环,但不能将该插件用于我正在解决的任务. (3认同)
  • 我真的很惊讶 2021 年 Javascript 没有提供一种简单的方法来测试像这样的 cookie,使用内置方法,您可以在其中添加 cookie 的名称作为参数。JS 有时是一种多么奇怪和愚蠢的语言啊。 (2认同)

cal*_*ack 6

请注意,如果 cookie 是安全的,则您无法使用document.cookie(所有答案都在使用)在客户端检查其存在。此类 cookie 只能在服务器端进行检查。

  • 我认为你的意思是[仅http](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) cookie。客户端仍然可以访问安全 cookie。 (3认同)

haj*_*mie 5

正则对象。test ( String )比 string匹配(正则表达式)。

所述MDN站点描述的document.cookie的格式,并且具有正则表达式示例抓住一个cookie( document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");)。基于此,我会这样做:

/^(.*;)?\s*cookie1\s*=/.test(document.cookie);
Run Code Online (Sandbox Code Playgroud)

该问题似乎要求一种解决方案,该解决方案在设置 cookie 时返回 false,但为空。在这种情况下:

/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);
Run Code Online (Sandbox Code Playgroud)

测试

/^(.*;)?\s*cookie1\s*=/.test(document.cookie);
Run Code Online (Sandbox Code Playgroud)

测试结果(Chrome 55.0.2883.87)