如何检查 cookie 是否存在?

发布于 2024-11-06 04:46:45 字数 286 浏览 2 评论 0原文

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

条件:

Cookie 存在,如果

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

Cookie 不存在,如果

cookie=;
//or
<blank>

What's a good way to check if a cookie exist?

Conditions:

Cookie exists if

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

Cookie doesn't exist if

cookie=;
//or
<blank>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

蝶…霜飞 2024-11-13 04:46:46

注意力!
所选答案包含错误(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, ''); 
}

ATTENTION!
the chosen answer contains a bug (Jac's answer).

if you have more than one cookie (very likely..) and the cookie you are retrieving is the first on the list, it doesn't set the variable "end" and therefore it will return the entire string of characters following the "cookieName=" within the document.cookie string!

here is a revised version of that function:

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, ''); 
}
浪菊怪哟 2024-11-13 04:46:46

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

获取特定 cookie 的值的方法如下:

$.cookie('MyCookie'); // Returns the cookie value

If you're using jQuery, you can use the jquery.cookie plugin.

Getting the value for a particular cookie is done as follows:

$.cookie('MyCookie'); // Returns the cookie value
凝望流年 2024-11-13 04:46:46

regexObject.测试(字符串)是比字符串更快匹配(正则表达式)。

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

/^(.*;)?\s*cookie1\s*=/.test(document.cookie);

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

/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);

测试

function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table(testCases.map(function(s){return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));

测试结果 (Chrome 55.0.2883.87)

regexObject.test( String ) is faster than string.match( RegExp ).

The MDN site describes the format for document.cookie, and has an example regex to grab a cookie (document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");). Based on that, I'd go for this:

/^(.*;)?\s*cookie1\s*=/.test(document.cookie);

The question seems to ask for a solution which returns false when the cookie is set, but empty. In that case:

/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);

Tests

function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table(testCases.map(function(s){return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));

Test results (Chrome 55.0.2883.87)

旧梦荧光笔 2024-11-13 04:46:46

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

Note that if a cookie is secure, you cannot check in client side for its existence using document.cookie (which all of the answers are using). Such cookie can be checked only at sever side.

壹場煙雨 2024-11-13 04:46:46

而不是 cookie 变量,您只需使用 document.cookie.split...

var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
  if(c.match(/cookie1=.+/))
   console.log(true);
});

instead of the cookie variable you would just use document.cookie.split...

var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
  if(c.match(/cookie1=.+/))
   console.log(true);
});

删除→记忆 2024-11-13 04:46:46

这里有几个很好的答案。然而,我更喜欢[1]不使用正则表达式,[2]使用易于阅读的逻辑,[3]使用有一个简短的函数,如果名称是另一个 cookie 名称的子字符串,[4] 不会返回 true。最后[5]我们不能使用foreach循环,因为return不会破坏它。

function cookieExists(name) {
  var cks = document.cookie.split(';');
  for(i = 0; i < cks.length; i++)
    if (cks[i].split('=')[0].trim() == name) return true;
}

There are several good answers here. I however prefer [1] not using a regular expression, and [2] using logic that is simple to read, and [3] to have a short function that [4] does not return true if the name is a substring of another cookie name . Lastly [5] we can't use a for each loop since a return doesn't break it.

function cookieExists(name) {
  var cks = document.cookie.split(';');
  for(i = 0; i < cks.length; i++)
    if (cks[i].split('=')[0].trim() == name) return true;
}
装纯掩盖桑 2024-11-13 04:46:46
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{
            var oneCookie = dc.indexOf(';', begin);
            if(oneCookie == -1){
                var end = dc.length;
            }else{
                var end = oneCookie;
            }
            return dc.substring(begin, end).replace(prefix,'');
        } 

    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
        var fixed = dc.substring(begin, end).replace(prefix,'');
    }
    // return decodeURI(dc.substring(begin + prefix.length, end));
    return fixed;
} 

尝试了@jac函数,遇到了一些麻烦,这是我编辑他的函数的方法。

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{
            var oneCookie = dc.indexOf(';', begin);
            if(oneCookie == -1){
                var end = dc.length;
            }else{
                var end = oneCookie;
            }
            return dc.substring(begin, end).replace(prefix,'');
        } 

    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
        var fixed = dc.substring(begin, end).replace(prefix,'');
    }
    // return decodeURI(dc.substring(begin + prefix.length, end));
    return fixed;
} 

Tried @jac function, got some trouble, here's how I edited his function.

橙味迷妹 2024-11-13 04:46:46

对于任何使用 Node 的人来说,我找到了一个很好且简单的解决方案,其中包含 ES6 导入和 cookie 模块!

首先安装cookie模块(并保存为依赖项):

npm install --save cookie

然后导入并使用:

import cookie from 'cookie';
let parsed = cookie.parse(document.cookie);
if('cookie1' in parsed) 
    console.log(parsed.cookie1);

For anyone using Node, I found a nice and simple solution with ES6 imports and the cookie module!

First install the cookie module (and save as a dependency):

npm install --save cookie

Then import and use:

import cookie from 'cookie';
let parsed = cookie.parse(document.cookie);
if('cookie1' in parsed) 
    console.log(parsed.cookie1);
眼中杀气 2024-11-13 04:46:46

使用 JavaScript:

 function getCookie(name) {
      let matches = document.cookie.match(new RegExp(
        "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
      ));
      return matches ? decodeURIComponent(matches[1]) : undefined;
    }

Using Javascript:

 function getCookie(name) {
      let matches = document.cookie.match(new RegExp(
        "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
      ));
      return matches ? decodeURIComponent(matches[1]) : undefined;
    }
怪我鬧 2024-11-13 04:46:46
// check if cookie is present 
function is_CookiePresent( cookieName ){

  if( void 0 != cookieName && "" != cookieName && null != cookieName ){

    var is_present = document.cookie.split(";").filter(e=>{
        if(e.trim().split("=").includes(cookieName)) return true;
    })

    if(!is_present.length){return false;}
    return true;

  }
  else{
    return false;
  }

}

// Get cookie name value :) 
function getCookieValue( cookieName ){

  if( void 0 != cookieName && "" != cookieName && null != cookieName ){

    var is_present = document.cookie.split(";").filter(e=>{
        if(e.trim().split("=").includes(cookieName)) return true;
    })

    if(!is_present.length){return false;}
   
    var __CookieValue = is_present.join('').trim();

    return __CookieValue.substring(__CookieValue.indexOf('=')+1);

  }
  else{
    return false;
  }

}
// check if cookie is present 
function is_CookiePresent( cookieName ){

  if( void 0 != cookieName && "" != cookieName && null != cookieName ){

    var is_present = document.cookie.split(";").filter(e=>{
        if(e.trim().split("=").includes(cookieName)) return true;
    })

    if(!is_present.length){return false;}
    return true;

  }
  else{
    return false;
  }

}

// Get cookie name value :) 
function getCookieValue( cookieName ){

  if( void 0 != cookieName && "" != cookieName && null != cookieName ){

    var is_present = document.cookie.split(";").filter(e=>{
        if(e.trim().split("=").includes(cookieName)) return true;
    })

    if(!is_present.length){return false;}
   
    var __CookieValue = is_present.join('').trim();

    return __CookieValue.substring(__CookieValue.indexOf('=')+1);

  }
  else{
    return false;
  }

}
森末i 2024-11-13 04:46:46

在 cookie 名称中添加一个空格作为前缀,并使用“=”作为后缀就可以了。

IsCookie("test");

function IsCookie(x) { return document.cookie.includes(" " + x + "=")}

Giving a space as prefix and "=" as suffix to the cookie name should do the job.

IsCookie("test");

function IsCookie(x) { return document.cookie.includes(" " + x + "=")}
零時差 2024-11-13 04:46:46
function getcookie(name = '') {
    let cookies = document.cookie;
    let cookiestore = {};
    
    cookies = cookies.split(";");
    
    if (cookies[0] == "" && cookies[0][0] == undefined) {
        return undefined;
    }
    
    cookies.forEach(function(cookie) {
        cookie = cookie.split(/=(.+)/);
        if (cookie[0].substr(0, 1) == ' ') {
            cookie[0] = cookie[0].substr(1);
        }
        cookiestore[cookie[0]] = cookie[1];
    });
    
    return (name !== '' ? cookiestore[name] : cookiestore);
}

要获取 cookie 对象,只需调用 getCookie()

要检查 cookie 是否存在,请执行以下操作:

if (!getcookie('myCookie')) {
    console.log('myCookie does not exist.');
} else {
    console.log('myCookie value is ' + getcookie('myCookie'));
}

或者仅使用三元运算符。

function getcookie(name = '') {
    let cookies = document.cookie;
    let cookiestore = {};
    
    cookies = cookies.split(";");
    
    if (cookies[0] == "" && cookies[0][0] == undefined) {
        return undefined;
    }
    
    cookies.forEach(function(cookie) {
        cookie = cookie.split(/=(.+)/);
        if (cookie[0].substr(0, 1) == ' ') {
            cookie[0] = cookie[0].substr(1);
        }
        cookiestore[cookie[0]] = cookie[1];
    });
    
    return (name !== '' ? cookiestore[name] : cookiestore);
}

To get a object of cookies simply call getCookie()

To check if a cookie exists, do it like this:

if (!getcookie('myCookie')) {
    console.log('myCookie does not exist.');
} else {
    console.log('myCookie value is ' + getcookie('myCookie'));
}

Or just use a ternary operator.

魂牵梦绕锁你心扉 2024-11-13 04:46:46

使用 Array.prototype 解析 cookie。减少()到一个对象(ES6)

const cookies = document.cookie.split(";").reduce((e, t) => {
  const [c, n] = t.trim().split("=").map(decodeURIComponent);
  try { // this can be removed if you do not need JSON cookies parsed
    return Object.assign(e, {
      [c]: JSON.parse(n)
    })
  }
  catch (t) {
    return Object.assign(e, {
      [c]: n
    })
  }
}, {})

检查你的cookie是否在那里

typeof cookies.yourCookie === "string";

Parse cookies with Array.prototype.reduce() into an object (ES6)

const cookies = document.cookie.split(";").reduce((e, t) => {
  const [c, n] = t.trim().split("=").map(decodeURIComponent);
  try { // this can be removed if you do not need JSON cookies parsed
    return Object.assign(e, {
      [c]: JSON.parse(n)
    })
  }
  catch (t) {
    return Object.assign(e, {
      [c]: n
    })
  }
}, {})

Check if your cookie is there

typeof cookies.yourCookie === "string";
-残月青衣踏尘吟 2024-11-13 04:46:46

如果有人仍在研究这篇文章,也许这会有所帮助。

首先执行一个函数来获取 cookie,类似这样..

function getCookie(cname) {
    let name = cname + "=";
    let ca = document.cookie.split(';');
    for(let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
    
  }

然后您可以在执行其他操作之前检查特定的 cookie 是否存在

if( getCookie(mycookieName)){
 // do something....
}

If anyone is still looking into this post maybe this will help.

First do a function to get the cookie, something like this..

function getCookie(cname) {
    let name = cname + "=";
    let ca = document.cookie.split(';');
    for(let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
    
  }

Then you could check if the specific cookie exists before doing something else

if( getCookie(mycookieName)){
 // do something....
}
各自安好 2024-11-13 04:46:46
const expirationDate = new Date()
expirationDate.setDate(expirationDate.getDate() + 7)
document.cookie = "name=John Doe; expires=" + expirationDate;

const cookie = document.cookie.split("; ").find((row) => row.startsWith("name="))?.split("=")[1];

工作完美,而且代码很短。如果为空,则 cookie 不存在或未设置。

const expirationDate = new Date()
expirationDate.setDate(expirationDate.getDate() + 7)
document.cookie = "name=John Doe; expires=" + expirationDate;

const cookie = document.cookie.split("; ").find((row) => row.startsWith("name="))?.split("=")[1];

Works perfect, and the code is short. If empty, the cookie does not exist or it is not set.

百变从容 2024-11-13 04:46:46

请改用此方法:

function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
    else return null;
}

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

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
    }
    else {
        // do cookie exists stuff
    }
}

use this method instead:

function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
    else return null;
}

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

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
    }
    else {
        // do cookie exists stuff
    }
}
浅笑依然 2024-11-13 04:46:46
/// ************************************************ cookie_exists

/// global entry point, export to global namespace

/// <synopsis>
///   cookie_exists ( name );
///
/// <summary>
///   determines if a cookie with name exists
///
/// <param name="name">
///   string containing the name of the cookie to test for 
//    existence
///
/// <returns>
///   true, if the cookie exists; otherwise, false
///
/// <example>
///   if ( cookie_exists ( name ) );
///     {
///     // do something with the existing cookie
///     }
///   else
///     {
///     // cookies does not exist, do something else 
///     }

function cookie_exists ( name )
  {
  var exists = false;

  if ( document.cookie )
    {
    if ( document.cookie.length > 0 )
      {
                                    // trim name
      if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
        {
        var cookies = document.cookie.split ( ";" );
        var name_with_equal = name + "=";

        for ( var i = 0; ( i < cookies.length ); i++ )
          {
                                    // trim cookie
          var cookie = cookies [ i ].replace ( /^\s*/, "" );

          if ( cookie.indexOf ( name_with_equal ) === 0 )
            {
            exists = true;
            break;
            }
          }
        }
      }
    }

  return ( exists );

  } // cookie_exists
/// ************************************************ cookie_exists

/// global entry point, export to global namespace

/// <synopsis>
///   cookie_exists ( name );
///
/// <summary>
///   determines if a cookie with name exists
///
/// <param name="name">
///   string containing the name of the cookie to test for 
//    existence
///
/// <returns>
///   true, if the cookie exists; otherwise, false
///
/// <example>
///   if ( cookie_exists ( name ) );
///     {
///     // do something with the existing cookie
///     }
///   else
///     {
///     // cookies does not exist, do something else 
///     }

function cookie_exists ( name )
  {
  var exists = false;

  if ( document.cookie )
    {
    if ( document.cookie.length > 0 )
      {
                                    // trim name
      if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
        {
        var cookies = document.cookie.split ( ";" );
        var name_with_equal = name + "=";

        for ( var i = 0; ( i < cookies.length ); i++ )
          {
                                    // trim cookie
          var cookie = cookies [ i ].replace ( /^\s*/, "" );

          if ( cookie.indexOf ( name_with_equal ) === 0 )
            {
            exists = true;
            break;
            }
          }
        }
      }
    }

  return ( exists );

  } // cookie_exists
明月松间行 2024-11-13 04:46:46
function hasCookie(cookieName){
return document.cookie.split(';')
.map(entry => entry.split('='))
.some(([name, value]) => (name.trim() === cookieName) && !!value);
}

注意:作者希望函数在 cookie 为空时返回 false,即 cookie=; 这是通过 && 实现的。 !!值 条件。如果您认为空 cookie 仍然是现有 cookie,请将其删除......

function hasCookie(cookieName){
return document.cookie.split(';')
.map(entry => entry.split('='))
.some(([name, value]) => (name.trim() === cookieName) && !!value);
}

Note: The author wanted the function to return false if the cookie is empty i.e. cookie=; this is achieved with the && !!value condition. Remove it if you consider an empty cookie is still an existing cookie…

嗫嚅 2024-11-13 04:46:46
var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
  if(c.match(/cookie1=.+/))
   console.log(true);
});

var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
  if(c.match(/cookie1=.+/))
   console.log(true);
});

似梦非梦 2024-11-13 04:46:46

您可以验证 cookie 是否存在并且它具有定义的值:

function getCookie(cookiename) {
    if (typeof(cookiename) == 'string' && cookiename != '') {
        const COOKIES = document.cookie.split(';');
        for (i = 0; i < COOKIES.length; i++) {
            if (COOKIES[i].trim().startsWith(cookiename)) {
                return COOKIES[i].split('=')[1];
            }
        }
    }

    return null;
}

const COOKIE_EXAMPLE = getCookie('example');
if (COOKIE_EXAMPLE == 'stackoverflow') { ... }
// If is set a cookie named "example" with value "stackoverflow"
if (COOKIE_EXAMPLE != null) { ... }
// If is set a cookie named "example" ignoring the value

如果 cookie 不存在,它将返回 null。

You can verify if a cookie exists and it has a defined value:

function getCookie(cookiename) {
    if (typeof(cookiename) == 'string' && cookiename != '') {
        const COOKIES = document.cookie.split(';');
        for (i = 0; i < COOKIES.length; i++) {
            if (COOKIES[i].trim().startsWith(cookiename)) {
                return COOKIES[i].split('=')[1];
            }
        }
    }

    return null;
}

const COOKIE_EXAMPLE = getCookie('example');
if (COOKIE_EXAMPLE == 'stackoverflow') { ... }
// If is set a cookie named "example" with value "stackoverflow"
if (COOKIE_EXAMPLE != null) { ... }
// If is set a cookie named "example" ignoring the value

It will return null if cookie doesn't exists.

尹雨沫 2024-11-13 04:46:45

您可以使用所需的 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
    }
}

You can call the function getCookie with the name of the cookie you want, then check to see if it is = 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
    }
}
浅语花开 2024-11-13 04:46:45

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

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

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

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

将您的 cookie 名称放在 MyCookie 的位置。

I have crafted an alternative non-jQuery version:

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

It only tests for cookie existence. A more complicated version can also return cookie value:

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

Put your cookie name in in place of MyCookie.

陈甜 2024-11-13 04:46:45
document.cookie.indexOf('cookie_name=');

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

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

(

document.cookie.indexOf('cookie_name=');

It will return -1 if that cookie does not exist.

p.s. Only drawback of it is (as mentioned in comments) that it will mistake if there is cookie set with such name: any_prefix_cookie_name

(Source)

慈悲佛祖 2024-11-13 04:46:45

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

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

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

cookie 永远不应该在没有值的情况下存在——因为,平心而论,这有什么意义呢?

This is an old question, but here's the approach I use ...

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

This returns null either when the cookie doesn't exist, or when it doesn't contain the requested name.
Otherwise, the value (of the requested name) is returned.

A cookie should never exist without a value -- because, in all fairness, what's the point of that? ????
If it's no longer needed, it's best to just get rid of it all together.

function deleteCookie(name) {
    document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文