按名称读取 javascript cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5142337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read a javascript cookie by name
提问by Jimbo
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')
}
回答by Paul Sweatte
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');
回答by lonesomeday
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
功能。
回答by usoban
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
资料来源:W3Schools
Edit: as @zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions
编辑:正如@zcrar70 所指出的,上面的代码是不正确的,请参阅以下答案Javascript getCookie 函数
回答by Escape75
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 与 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 扩展中使用它,所以我知道我正在设置的名称,并且我可以确保或多或少不会重复。
回答by rahulroy9202
using jquery-cookie
使用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');
回答by Dimos
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.cookieas 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"];
回答by Joseph Myers
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
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
.
这为 保存了绿色gardens.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 的网址的域相同。
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.
还通过执行 删除 cookie makeCookie('rememberlogin', '', { expires: -1 })
。这使得 cookie 代码更长,但为使用它的人节省了代码,从长远来看,人们可能认为这节省了更多的代码。
回答by japetko
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');
}
}
回答by JAAulde
Here is an API which was written to smooth over the nasty browser cookie "API"
这是一个 API,它被编写用来消除讨厌的浏览器 cookie“API”
回答by craftsmannadeem
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;
};
})();