document.cookie

Summary

Get and set the cookies associated with the current document.

Syntax

allCookies = document.cookie;
  • allCookies is a string containing a semicolon-separated list of cookies (i.e. key=value pairs)
document.cookie = updatedCookie;
  • updatedCookie is a string of form key=value. Note that you can only set/update a single cookie at a time using this method.
  • Any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator:
    • ;path=path (e.g., '/', '/mydir') If not specified, defaults to the current path of the current document location.
    • ;domain=domain (e.g., 'example.com', '.example.com' (includes all subdomains), 'subdomain.example.com') If not specified, defaults to the host portion of the current document location.
    • ;max-age=max-age-in-seconds (e.g., 60*60*24*365 for a year)
    • ;expires=date-in-GMTString-format If not specified it will expire at the end of session.
    • ;secure (cookie to only be transmitted over secure protocol as https)
  • The cookie value string can use encodeURIComponent() to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values).

Gecko 6.0 note
(Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3)

Note that prior to Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) , paths with quotes were treated as if the quotes were part of the string, instead of as if they were delimiters surrounding the actual path string. This has been fixed.

Example

Simple usage:

  1. document.cookie = "name=oeschger";  
  2. document.cookie = "favorite_food=tripe";  
  3. alert(document.cookie);  
  4. // displays: name=oeschger;favorite_food=tripe  

A complete cookies reader/writer:

  1. docCookies = {  
  2.   getItem: function (sKey) {  
  3.     if (!sKey || !this.hasItem(sKey)) { return null; }  
  4.     return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));  
  5.   },  
  6.   /** 
  7.   * docCookies.setItem(sKey, sValue, vEnd, sPath, sDomain, bSecure) 
  8.   * 
  9.   * @argument sKey (String): the name of the cookie; 
  10.   * @argument sValue (String): the value of the cookie; 
  11.   * @optional argument vEnd (Number, String, Date Object or null): the max-age in seconds (e.g., 31536e3 for a year) or the 
  12.   *  expires date in GMTString format or in Date Object format; if not specified it will expire at the end of session;  
  13.   * @optional argument sPath (String or null): e.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location; 
  14.   * @optional argument sDomain (String or null): e.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com"; if not 
  15.   * specified, defaults to the host portion of the current document location; 
  16.   * @optional argument bSecure (Boolean or null): cookie will be transmitted only over secure protocol as https; 
  17.   * @return undefined; 
  18.   **/  
  19.   setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {  
  20.     if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }  
  21.     var sExpires = "";  
  22.     if (vEnd) {  
  23.       switch (typeof vEnd) {  
  24.         case "number": sExpires = "; max-age=" + vEnd; break;  
  25.         case "string": sExpires = "; expires=" + vEnd; break;  
  26.         case "object"if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;  
  27.       }  
  28.     }  
  29.     document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");  
  30.   },  
  31.   removeItem: function (sKey) {  
  32.     if (!sKey || !this.hasItem(sKey)) { return; }  
  33.     var oExpDate = new Date();  
  34.     oExpDate.setDate(oExpDate.getDate() - 1);  
  35.     document.cookie = escape(sKey) + "=; expires=" + oExpDate.toGMTString() + "; path=/";  
  36.   },  
  37.   hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }  
  38. };  
  39.   
  40. // docCookies.setItem("test1", "Hello world!");  
  41. // docCookies.setItem("test2", "Hello world!", new Date(2020, 5, 12));  
  42. // docCookies.setItem("test3", "Hello world!", new Date(2027, 2, 3), "/blog");  
  43. // docCookies.setItem("test4", "Hello world!", "Sun, 06 Nov 2022 21:43:15 GMT");  
  44. // docCookies.setItem("test5", "Hello world!", "Tue, 06 Dec 2022 13:11:07 GMT", "/home");  
  45. // docCookies.setItem("test6", "Hello world!", 150);  
  46. // docCookies.setItem("test7", "Hello world!", 245, "/content");  
  47. // docCookies.setItem("test8", "Hello world!", null, null, "example.com");  
  48. // docCookies.setItem("test9", "Hello world!", null, null, null, true);  
  49.   
  50. // alert(docCookies.getItem("test1"));  

源自:https://developer.mozilla.org/en/DOM/document.cookie

Security

It is important to note that the path restriction does not protect against unauthorized reading of the cookie from a different path. It can easily be bypassed with simple DOM (for example by creating a hidden iframe element with the path of the cookie, then accessing this iframe's contentDocument.cookie property). The only way to protect cookie access is by using a different domain or subdomain, due to the same origin policy.

Notes

  • Starting with Firefox 2, a better mechanism for client-side storage is available - WHATWG DOM Storage.
  • You can delete a cookie by simply updating its expiration time to zero.
  • Keep in mind that the more you have cookies the more data will be transferred between the server and the client for each request. This will make each request slower. It is highly recommended for you to use WHATWG DOM Storage if you are going to keep "client-only" data.

See also

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值