[英]How do I check if a cookie exists?
检查 cookie 是否存在的好方法是什么?
状况:
Cookie 存在如果
cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
Cookie 不存在,如果
cookie=;
//or
<blank>
您可以使用您想要的 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
}
}
我制作了一个替代的非 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.indexOf('cookie_name=');
如果该 cookie 不存在,它将返回-1
。
ps 唯一的缺点是(如评论中所述)如果设置了这样的名称的 cookie 会出错: any_prefix_cookie_name
(来源)
注意力! 选择的答案包含一个错误(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, '');
}
这是一个老问题,但这是我使用的方法......
function getCookie(name) {
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
return match ? match[1] : null;
}
当 cookie 不存在或不包含请求的名称时,这将返回null
。
否则,返回(请求名称的)值。
没有值的 cookie 永远不应该存在——因为,平心而论,那有什么意义呢? 😄
如果不再需要它,最好一起摆脱它。
function deleteCookie(name) {
document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
如果您使用 jQuery,则可以使用jquery.cookie 插件。
获取特定 cookie 的值按如下方式完成:
$.cookie('MyCookie'); // Returns the cookie value
正则对象。 test ( String ) 比 string快。 匹配(正则表达式)。
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)}}));
这里有几个很好的答案。 但是我更喜欢[1]不使用正则表达式,和[2]使用的逻辑是简单阅读,和[3]具有短函数[4]不返回true,如果名字是另一个的cookie的子串姓名 。 最后[5]我们不能为每个循环使用 a,因为 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;
}
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 函数,遇到了一些麻烦,这是我编辑他的函数的方法。
而不是 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); });
对于任何使用 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);
使用 JavaScript:
function getCookie(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
请注意,如果 cookie 是安全的,则您无法使用document.cookie
(所有答案都在使用)检查客户端是否存在。 此类 cookie 只能在服务器端检查。
使用Array.prototype.reduce()
将 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";
如果有人仍在查看这篇文章,也许这会有所帮助。
首先做一个函数来获取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....
}
// 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;
}
}
请改用此方法:
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
}
}
/// ************************************************ 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
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 hasCookie(cookieName){
return document.cookie.split(';')
.map(entry => entry.split('='))
.some(([name, value]) => (name.trim() === cookieName) && !!value);
}
注意:作者希望函数在 cookie 为空时返回 false,即cookie=;
这是通过&& !!value
条件实现的。 如果您认为空 cookie 仍然是现有 cookie,请删除它……
var cookie = 'cookie1=s; cookie1=; cookie2=test'; var cookies = cookie.split('; '); cookies.forEach(function(c){ if(c.match(/cookie1=.+/)) console.log(true); });
您可以验证 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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.