document.cookie

本文介绍如何使用document.cookie属性来获取和设置浏览器中的Cookies。包括简单的示例代码和完整的Cookies读写器实现,涵盖设置路径、域名、过期时间等属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Summary

Get and set the cookies associated with the current document.

Syntax

allCookies = document.cookie;
  • allCookiesis a string containing a semicolon-separated list of cookies (i.e.key=valuepairs)
document.cookie = updatedCookie;
  • updatedCookieis a string of formkey=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-formatIf 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 useencodeURIComponent()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)){returnnull;}
  4. returnunescape(document.cookie.replace(newRegExp("(?:^|.*;\\s*)"+escape(sKey).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"),"$1"));
  5. },
  6. /**
  7. *docCookies.setItem(sKey,sValue,vEnd,sPath,sDomain,bSecure)
  8. *
  9. *@argumentsKey(String):thenameofthecookie;
  10. *@argumentsValue(String):thevalueofthecookie;
  11. *@optionalargumentvEnd(Number,String,DateObjectornull):themax-ageinseconds(e.g.,31536e3forayear)orthe
  12. *expiresdateinGMTStringformatorinDateObjectformat;ifnotspecifieditwillexpireattheendofsession;
  13. *@optionalargumentsPath(Stringornull):e.g.,"/","/mydir";ifnotspecified,defaultstothecurrentpathofthecurrentdocumentlocation;
  14. *@optionalargumentsDomain(Stringornull):e.g.,"example.com",".example.com"(includesallsubdomains)or"subdomain.example.com";ifnot
  15. *specified,defaultstothehostportionofthecurrentdocumentlocation;
  16. *@optionalargumentbSecure(Booleanornull):cookiewillbetransmittedonlyoversecureprotocolashttps;
  17. *@returnundefined;
  18. **/
  19. setItem:function(sKey,sValue,vEnd,sPath,sDomain,bSecure){
  20. if(!sKey||/^(?:expires|max\-age|path|domain|secure)$/.test(sKey)){return;}
  21. varsExpires="";
  22. if(vEnd){
  23. switch(typeofvEnd){
  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. varoExpDate=newDate();
  34. oExpDate.setDate(oExpDate.getDate()-1);
  35. document.cookie=escape(sKey)+"=;expires="+oExpDate.toGMTString()+";path=/";
  36. },
  37. hasItem:function(sKey){return(newRegExp("(?:^|;\\s*)"+escape(sKey).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=")).test(document.cookie);}
  38. };
  39. //docCookies.setItem("test1","Helloworld!");
  40. //docCookies.setItem("test2","Helloworld!",newDate(2020,5,12));
  41. //docCookies.setItem("test3","Helloworld!",newDate(2027,2,3),"/blog");
  42. //docCookies.setItem("test4","Helloworld!","Sun,06Nov202221:43:15GMT");
  43. //docCookies.setItem("test5","Helloworld!","Tue,06Dec202213:11:07GMT","/home");
  44. //docCookies.setItem("test6","Helloworld!",150);
  45. //docCookies.setItem("test7","Helloworld!",245,"/content");
  46. //docCookies.setItem("test8","Helloworld!",null,null,"example.com");
  47. //docCookies.setItem("test9","Helloworld!",null,null,null,true);
  48. //alert(docCookies.getItem("test1"));

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

Security

It is important to note that thepathrestriction doesnotprotect against unauthorized reading of the cookie from a different path. It can easily be bypassed with simple DOM (for example by creating a hiddeniframeelement with the path of the cookie, then accessing this iframe'scontentDocument.cookieproperty). The only way to protect cookie access is by using a different domain or subdomain, due to thesame 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 useWHATWG DOM Storageif you are going to keep "client-only" data.

See also

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值