I have set a cookie using
我已经设置了一个cookie
document.cookie =
'MYBIGCOOKIE=' + value +
'; expires=' + now.toGMTString() +
'; path=/';
Now there are between 5 and 10 cookies set on this site, is there a way to check the value ofthis cookie by name.
现在这个网站上设置了5到10个cookie,有没有办法按名称检查这个cookie的值。
if (document.cookie.MYBIGCOOKIE == '1') {
alert('it is 1')
}
10 个解决方案
#1
17
Use the RegExp constructor and multiple replacements to clarify the syntax:
使用RegExp构造函数和多个替换来阐明语法:
function getCook(cookiename)
{
// Get name followed by anything except a semicolon
var cookiestring=RegExp(""+cookiename+"[^;]+").exec(document.cookie);
// Return everything after the equal sign, or an empty string if the cookie name not found
return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}
//Sample usage
var cookieValue = getCook('MYBIGCOOKIE');
#2
13
Unfortunately, Javascript's cookie syntax is nowhere near as nice as that. In fact, in my opinion, it's one of the worst designed parts.
不幸的是,Javascript的cookie语法远没有那么好。事实上,在我看来,它是设计最差的部分之一。
When you try to read document.cookie
, you get a string containing all the cookies set. You have to parse the string, separating by the semicolon ;
character. Rather than writing this yourself, there are plenty of versions available on the web. My favourite is the one at quirksmode.org. This gives you createCookie
, readCookie
and deleteCookie
functions.
当您尝试阅读document.cookie时,您会收到一个包含所有Cookie集的字符串。你必须解析字符串,用分号分隔;字符。网络上有很多版本,而不是自己编写。我最喜欢的是quirksmode.org上的那个。这为您提供了createCookie,readCookie和deleteCookie函数。
#3
9
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Source: W3Schools
Edit: as @zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions
编辑:如@ zcrar70所述,上面的代码不正确,请看下面的答案Javascript getCookie函数
#4
3
using jquery-cookie
I find this library helpful. 3.128 kb of pure convenience.
我觉得这个图书馆很有用。 3.128 kb纯粹的便利。
add script
<script src="/path/to/jquery.cookie.js"></script>
set cookie
$.cookie('name', 'value');
read cookie
$.cookie('name');
#5
2
The point of Stack Overflow is to provide a database of good quality answers, so I am going to reference some standard source code and an article that gives examples:
Stack Overflow的目的是提供一个高质量答案的数据库,所以我将引用一些标准源代码和一篇提供示例的文章:
http://www.codelib.net/javascript/cookies.html
Note: The code is regular-expression free for greatly enhanced efficiency.
注意:代码是正则表达式,可大大提高效率。
Using the source code provided, you would use cookies like this:
使用提供的源代码,您将使用以下cookie:
makeCookie('color', 'silver');
This saves a cookie indicating that the color is silver. The cookie would expire after the current session (as soon as the user quits the browser).
这会保存一个cookie,表明颜色是银色。 cookie将在当前会话之后到期(一旦用户退出浏览器)。
makeCookie('color', 'green', { domain: 'gardens.home.com' });
This saves the color green for gardens.home.com
.
这为garden.home.com保留了绿色。
makeCookie('color', 'white', { domain: '.home.com', path: '/invoices' });
makeCookie('invoiceno', '0259876', { path: '/invoices', secure: true });
saves the color white for invoices viewed anywhere at home.com. The second cookie is a secure cookie, and records an invoice number. This cookie will be sent only to pages that are viewed through secure HTTPS connections, and scripts within secure pages are the only scripts allowed to access the cookie.
为home.com上任何位置查看的发票保存白色。第二个cookie是安全cookie,并记录发票号。此cookie将仅发送到通过安全HTTPS连接查看的页面,安全页面中的脚本是唯一允许访问cookie的脚本。
One HTTP host is not allowed to store or read cookies for another HTTP host. Thus, a cookie domain must be stored with at least two periods. By default, the domain is the same as the domain of the web address which created the cookie.
不允许一个HTTP主机存储或读取另一个HTTP主机的cookie。因此,cookie域必须至少存储两个句点。默认情况下,域与创建cookie的Web地址的域相同。
The path of an HTTP cookie restricts it to certain files on the HTTP host. Some browsers use a default path of /
, so the cookie will be available on the whole host. Other browsers use the whole filename. In this case, if /invoices/overdue.cgi
creates a cookie, only /invoices/overdue.cgi
is going to get the cookie back.
HTTP cookie的路径将其限制为HTTP主机上的某些文件。某些浏览器使用默认路径/,因此cookie将在整个主机上可用。其他浏览器使用整个文件名。在这种情况下,如果/invoices/overdue.cgi创建了一个cookie,那么只有/invoices/overdue.cgi会返回cookie。
When setting paths and other parameters, they are usually based on data obtained from variables like location.href, etc. These strings are already escaped, so when the cookie is created, the cookie function does not escape these values again. Only the name and value of the cookie are escaped, so we can conveniently use arbitrary names or values. Some browsers limit the total size of a cookie, or the total number of cookies which one domain is allowed to keep.
设置路径和其他参数时,它们通常基于从location.href等变量获得的数据。这些字符串已经被转义,因此在创建cookie时,cookie函数不会再次转义这些值。只转义cookie的名称和值,因此我们可以方便地使用任意名称或值。某些浏览器会限制Cookie的总大小,或允许一个域保留的Cookie总数。
makeCookie('rememberemail', 'yes', { expires: 7 });
makeCookie('rememberlogin', 'yes', { expires: 1 });
makeCookie('allowentergrades', 'yes', { expires: 1/24 });
these cookies would remember the user's email for 7 days, the user's login for 1 day, and allow the user to enter grades without a password for 1 hour (a twenty-fourth of a day). These time limits are obeyed even if they quit the browser, and even if they don't quit the browser. Users are free to use a different browser program, or to delete cookies. If they do this, the cookies will have no effect, regardless of the expiration date.
这些cookie会记住用户的电子邮件7天,用户登录1天,并允许用户在没有密码的情况下输入1小时(一天中的第24天)的成绩。即使他们退出浏览器,即使他们不退出浏览器,也会遵守这些时间限制。用户可以*使用其他浏览器程序,也可以删除cookie。如果他们这样做,无论到期日期如何,cookie都将无效。
makeCookie('rememberlogin', 'yes', { expires: -1 });
deletes the cookie. The cookie value is superfluous, and the return value false means that deletion was successful. (A expiration of -1 is used instead of 0. If we had used 0, the cookie might be undeleted until one second past the current time. In this case we would think that deletion was unsuccessful.)
删除cookie。 cookie值是多余的,返回值false表示删除成功。 (使用-1的到期而不是0.如果我们使用0,则cookie可能会被取消删除,直到超过当前时间一秒。在这种情况下,我们认为删除不成功。)
Obviously, since a cookie can be deleted in this way, a new cookie will also overwrite any value of an old cookie which has the same name, including the expiration date, etc. However, cookies for completely non-overlapping paths or domains are stored separately, and the same names do not interfere with each other. But in general, any path or domain which has access to a cookie can overwrite the cookie, no matter whether or not it changes the path or domain of the new cookie.
显然,由于可以通过这种方式删除cookie,因此新cookie也会覆盖具有相同名称的旧cookie的任何值,包括到期日期等。但是,存储完全不重叠的路径或域的cookie分开,并且相同的名称不会相互干扰。但一般来说,任何有权访问cookie的路径或域都可以覆盖cookie,无论它是否改变了新cookie的路径或域。
rmCookie('rememberlogin');
also deletes the cookie, by doing makeCookie('rememberlogin', '', { expires: -1 })
. This makes the cookie code longer, but saves code for people who use it, which one might think saves more code in the long run.
也可以通过makeCookie('rememberlogin','',{expires:-1})来删除cookie。这使得cookie代码更长,但为使用它的人保存代码,从长远来看,人们可能认为可以节省更多代码。
#6
2
document.cookie="MYBIGCOOKIE=1";
Your cookies would look like:
您的Cookie看起来像:
"MYBIGCOOKIE=1; PHPSESSID=d76f00dvgrtea8f917f50db8c31cce9"
first of all read all cookies:
首先阅读所有cookies:
var read_cookies = document.cookie;
then split all cookies with ";":
然后用“;”分割所有cookie:
var split_read_cookie = read_cookies.split(";");
then use for loop to read each value. Into loop each value split again with "=":
然后使用for循环来读取每个值。进入循环,每个值再次以“=”分割:
for (i=0;i<split_read_cookie.length;i++){
var value=split_read_cookie[i];
value=value.split("=");
if(value[0]=="MYBIGCOOKIE" && value[1]=="1"){
alert('it is 1');
}
}
#7
1
Here is an API which was written to smooth over the nasty browser cookie "API"
这是一个API,用于平滑令人讨厌的浏览器cookie“API”
#8
1
You can use the following function:
您可以使用以下功能:
function getCookiesMap(cookiesString) {
return cookiesString.split(";")
.map(function(cookieString) {
return cookieString.trim().split("=");
})
.reduce(function(acc, curr) {
acc[curr[0]] = curr[1];
return acc;
}, {});
}
When, called with document.cookie as parameter, it will return an object, with the cookies keys as keys and the cookies values.
当使用document.cookie作为参数调用时,它将返回一个对象,其中cookie键作为键和cookie值。
var cookies = getCookiesMap(document.cookie);
var cookieValue = cookies["MYBIGCOOKIE"];
#9
1
One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):
最简单的方法之一是,但如前所述,如果有相似的名称(MyCookie vs AnotherMyCookie),它可以返回错误的cookie:
var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];
I use this in a chrome extension so I know the name I'm setting, and I can make sure there won't be a duplicate, more or less.
我在chrome扩展中使用它,所以我知道我正在设置的名称,我可以确保不会有重复,或多或少。
#10
0
Here is an example implementation, which would make this process seamless (Borrowed from AngularJs)
这是一个示例实现,它将使这个过程无缝(借用AngularJs)
var CookieReader = (function(){
var lastCookies = {};
var lastCookieString = '';
function safeGetCookie() {
try {
return document.cookie || '';
} catch (e) {
return '';
}
}
function safeDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}
function isUndefined(value) {
return typeof value === 'undefined';
}
return function () {
var cookieArray, cookie, i, index, name;
var currentCookieString = safeGetCookie();
if (currentCookieString !== lastCookieString) {
lastCookieString = currentCookieString;
cookieArray = lastCookieString.split('; ');
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
name = safeDecodeURIComponent(cookie.substring(0, index));
if (isUndefined(lastCookies[name])) {
lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
};
})();
#1
17
Use the RegExp constructor and multiple replacements to clarify the syntax:
使用RegExp构造函数和多个替换来阐明语法:
function getCook(cookiename)
{
// Get name followed by anything except a semicolon
var cookiestring=RegExp(""+cookiename+"[^;]+").exec(document.cookie);
// Return everything after the equal sign, or an empty string if the cookie name not found
return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}
//Sample usage
var cookieValue = getCook('MYBIGCOOKIE');
#2
13
Unfortunately, Javascript's cookie syntax is nowhere near as nice as that. In fact, in my opinion, it's one of the worst designed parts.
不幸的是,Javascript的cookie语法远没有那么好。事实上,在我看来,它是设计最差的部分之一。
When you try to read document.cookie
, you get a string containing all the cookies set. You have to parse the string, separating by the semicolon ;
character. Rather than writing this yourself, there are plenty of versions available on the web. My favourite is the one at quirksmode.org. This gives you createCookie
, readCookie
and deleteCookie
functions.
当您尝试阅读document.cookie时,您会收到一个包含所有Cookie集的字符串。你必须解析字符串,用分号分隔;字符。网络上有很多版本,而不是自己编写。我最喜欢的是quirksmode.org上的那个。这为您提供了createCookie,readCookie和deleteCookie函数。
#3
9
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Source: W3Schools
Edit: as @zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions
编辑:如@ zcrar70所述,上面的代码不正确,请看下面的答案Javascript getCookie函数
#4
3
using jquery-cookie
I find this library helpful. 3.128 kb of pure convenience.
我觉得这个图书馆很有用。 3.128 kb纯粹的便利。
add script
<script src="/path/to/jquery.cookie.js"></script>
set cookie
$.cookie('name', 'value');
read cookie
$.cookie('name');
#5
2
The point of Stack Overflow is to provide a database of good quality answers, so I am going to reference some standard source code and an article that gives examples:
Stack Overflow的目的是提供一个高质量答案的数据库,所以我将引用一些标准源代码和一篇提供示例的文章:
http://www.codelib.net/javascript/cookies.html
Note: The code is regular-expression free for greatly enhanced efficiency.
注意:代码是正则表达式,可大大提高效率。
Using the source code provided, you would use cookies like this:
使用提供的源代码,您将使用以下cookie:
makeCookie('color', 'silver');
This saves a cookie indicating that the color is silver. The cookie would expire after the current session (as soon as the user quits the browser).
这会保存一个cookie,表明颜色是银色。 cookie将在当前会话之后到期(一旦用户退出浏览器)。
makeCookie('color', 'green', { domain: 'gardens.home.com' });
This saves the color green for gardens.home.com
.
这为garden.home.com保留了绿色。
makeCookie('color', 'white', { domain: '.home.com', path: '/invoices' });
makeCookie('invoiceno', '0259876', { path: '/invoices', secure: true });
saves the color white for invoices viewed anywhere at home.com. The second cookie is a secure cookie, and records an invoice number. This cookie will be sent only to pages that are viewed through secure HTTPS connections, and scripts within secure pages are the only scripts allowed to access the cookie.
为home.com上任何位置查看的发票保存白色。第二个cookie是安全cookie,并记录发票号。此cookie将仅发送到通过安全HTTPS连接查看的页面,安全页面中的脚本是唯一允许访问cookie的脚本。
One HTTP host is not allowed to store or read cookies for another HTTP host. Thus, a cookie domain must be stored with at least two periods. By default, the domain is the same as the domain of the web address which created the cookie.
不允许一个HTTP主机存储或读取另一个HTTP主机的cookie。因此,cookie域必须至少存储两个句点。默认情况下,域与创建cookie的Web地址的域相同。
The path of an HTTP cookie restricts it to certain files on the HTTP host. Some browsers use a default path of /
, so the cookie will be available on the whole host. Other browsers use the whole filename. In this case, if /invoices/overdue.cgi
creates a cookie, only /invoices/overdue.cgi
is going to get the cookie back.
HTTP cookie的路径将其限制为HTTP主机上的某些文件。某些浏览器使用默认路径/,因此cookie将在整个主机上可用。其他浏览器使用整个文件名。在这种情况下,如果/invoices/overdue.cgi创建了一个cookie,那么只有/invoices/overdue.cgi会返回cookie。
When setting paths and other parameters, they are usually based on data obtained from variables like location.href, etc. These strings are already escaped, so when the cookie is created, the cookie function does not escape these values again. Only the name and value of the cookie are escaped, so we can conveniently use arbitrary names or values. Some browsers limit the total size of a cookie, or the total number of cookies which one domain is allowed to keep.
设置路径和其他参数时,它们通常基于从location.href等变量获得的数据。这些字符串已经被转义,因此在创建cookie时,cookie函数不会再次转义这些值。只转义cookie的名称和值,因此我们可以方便地使用任意名称或值。某些浏览器会限制Cookie的总大小,或允许一个域保留的Cookie总数。
makeCookie('rememberemail', 'yes', { expires: 7 });
makeCookie('rememberlogin', 'yes', { expires: 1 });
makeCookie('allowentergrades', 'yes', { expires: 1/24 });
these cookies would remember the user's email for 7 days, the user's login for 1 day, and allow the user to enter grades without a password for 1 hour (a twenty-fourth of a day). These time limits are obeyed even if they quit the browser, and even if they don't quit the browser. Users are free to use a different browser program, or to delete cookies. If they do this, the cookies will have no effect, regardless of the expiration date.
这些cookie会记住用户的电子邮件7天,用户登录1天,并允许用户在没有密码的情况下输入1小时(一天中的第24天)的成绩。即使他们退出浏览器,即使他们不退出浏览器,也会遵守这些时间限制。用户可以*使用其他浏览器程序,也可以删除cookie。如果他们这样做,无论到期日期如何,cookie都将无效。
makeCookie('rememberlogin', 'yes', { expires: -1 });
deletes the cookie. The cookie value is superfluous, and the return value false means that deletion was successful. (A expiration of -1 is used instead of 0. If we had used 0, the cookie might be undeleted until one second past the current time. In this case we would think that deletion was unsuccessful.)
删除cookie。 cookie值是多余的,返回值false表示删除成功。 (使用-1的到期而不是0.如果我们使用0,则cookie可能会被取消删除,直到超过当前时间一秒。在这种情况下,我们认为删除不成功。)
Obviously, since a cookie can be deleted in this way, a new cookie will also overwrite any value of an old cookie which has the same name, including the expiration date, etc. However, cookies for completely non-overlapping paths or domains are stored separately, and the same names do not interfere with each other. But in general, any path or domain which has access to a cookie can overwrite the cookie, no matter whether or not it changes the path or domain of the new cookie.
显然,由于可以通过这种方式删除cookie,因此新cookie也会覆盖具有相同名称的旧cookie的任何值,包括到期日期等。但是,存储完全不重叠的路径或域的cookie分开,并且相同的名称不会相互干扰。但一般来说,任何有权访问cookie的路径或域都可以覆盖cookie,无论它是否改变了新cookie的路径或域。
rmCookie('rememberlogin');
also deletes the cookie, by doing makeCookie('rememberlogin', '', { expires: -1 })
. This makes the cookie code longer, but saves code for people who use it, which one might think saves more code in the long run.
也可以通过makeCookie('rememberlogin','',{expires:-1})来删除cookie。这使得cookie代码更长,但为使用它的人保存代码,从长远来看,人们可能认为可以节省更多代码。
#6
2
document.cookie="MYBIGCOOKIE=1";
Your cookies would look like:
您的Cookie看起来像:
"MYBIGCOOKIE=1; PHPSESSID=d76f00dvgrtea8f917f50db8c31cce9"
first of all read all cookies:
首先阅读所有cookies:
var read_cookies = document.cookie;
then split all cookies with ";":
然后用“;”分割所有cookie:
var split_read_cookie = read_cookies.split(";");
then use for loop to read each value. Into loop each value split again with "=":
然后使用for循环来读取每个值。进入循环,每个值再次以“=”分割:
for (i=0;i<split_read_cookie.length;i++){
var value=split_read_cookie[i];
value=value.split("=");
if(value[0]=="MYBIGCOOKIE" && value[1]=="1"){
alert('it is 1');
}
}
#7
1
Here is an API which was written to smooth over the nasty browser cookie "API"
这是一个API,用于平滑令人讨厌的浏览器cookie“API”
#8
1
You can use the following function:
您可以使用以下功能:
function getCookiesMap(cookiesString) {
return cookiesString.split(";")
.map(function(cookieString) {
return cookieString.trim().split("=");
})
.reduce(function(acc, curr) {
acc[curr[0]] = curr[1];
return acc;
}, {});
}
When, called with document.cookie as parameter, it will return an object, with the cookies keys as keys and the cookies values.
当使用document.cookie作为参数调用时,它将返回一个对象,其中cookie键作为键和cookie值。
var cookies = getCookiesMap(document.cookie);
var cookieValue = cookies["MYBIGCOOKIE"];
#9
1
One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):
最简单的方法之一是,但如前所述,如果有相似的名称(MyCookie vs AnotherMyCookie),它可以返回错误的cookie:
var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];
I use this in a chrome extension so I know the name I'm setting, and I can make sure there won't be a duplicate, more or less.
我在chrome扩展中使用它,所以我知道我正在设置的名称,我可以确保不会有重复,或多或少。
#10
0
Here is an example implementation, which would make this process seamless (Borrowed from AngularJs)
这是一个示例实现,它将使这个过程无缝(借用AngularJs)
var CookieReader = (function(){
var lastCookies = {};
var lastCookieString = '';
function safeGetCookie() {
try {
return document.cookie || '';
} catch (e) {
return '';
}
}
function safeDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}
function isUndefined(value) {
return typeof value === 'undefined';
}
return function () {
var cookieArray, cookie, i, index, name;
var currentCookieString = safeGetCookie();
if (currentCookieString !== lastCookieString) {
lastCookieString = currentCookieString;
cookieArray = lastCookieString.split('; ');
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
name = safeDecodeURIComponent(cookie.substring(0, index));
if (isUndefined(lastCookies[name])) {
lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
};
})();