document.cookie

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

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

【无人机】基于改进粒子群算法的无人机路径规划研究[和遗传算法、粒子群算法进行比较](Matlab代码实现)内容概要:本文围绕基于改进粒子群算法的无人机路径规划展开研究,重点探讨了在复杂环境中利用改进粒子群算法(PSO)实现无人机三维路径规划的方法,并将其与遗传算法(GA)、标准粒子群算法等传统优化算法进行对比分析。研究内容涵盖路径规划的多目标优化、避障策略、航路点约束以及算法收敛性和寻优能力的评估,所有实验均通过Matlab代码实现,提供了完整的仿真验证流程。文章还提到了多种智能优化算法在无人机路径规划中的应用比较,突出了改进PSO在收敛速度和全局寻优方面的优势。; 适合人群:具备一定Matlab编程基础和优化算法知识的研究生、科研人员及从事无人机路径规划、智能优化算法研究的相关技术人员。; 使用场景及目标:①用于无人机在复杂地形或动态环境下的三维路径规划仿真研究;②比较不同智能优化算法(如PSO、GA、蚁群算法、RRT等)在路径规划中的性能差异;③为多目标优化问题提供算法选型和改进思路。; 阅读建议:建议读者结合文中提供的Matlab代码进行实践操作,重点关注算法的参数设置、适应度函数设计及路径约束处理方式,同时可参考文中提到的多种算法对比思路,拓展到其他智能优化算法的研究与改进中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值