检查 cookie 是否存在的好方法是什么?
条件:
Cookie 存在,如果
cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
如果 Cookie 不存在
cookie=;
//or
<blank>
检查 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=');
-1
如果该 cookie 不存在,它将返回。
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;
}
这将null
在 cookie 不存在或不包含请求的名称时返回。
否则,返回(请求名称的)值。
没有value的 cookie 永远不应该存在——因为,平心而论,那有什么意义呢?😄
如果不再需要它,最好一起摆脱它。
function deleteCookie(name) {
document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}