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 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-format
If not specified it will expire at the end of session.- SeeDate.toUTCString()for help formatting this value.
-
;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).
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:
- document.cookie="name=oeschger";
- document.cookie="favorite_food=tripe";
- alert(document.cookie);
- //displays:name=oeschger;favorite_food=tripe
A complete cookies reader/writer:
- docCookies={
- getItem:function(sKey){
- if(!sKey||!this.hasItem(sKey)){returnnull;}
- returnunescape(document.cookie.replace(newRegExp("(?:^|.*;\\s*)"+escape(sKey).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"),"$1"));
- },
- /**
- *docCookies.setItem(sKey,sValue,vEnd,sPath,sDomain,bSecure)
- *
- *@argumentsKey(String):thenameofthecookie;
- *@argumentsValue(String):thevalueofthecookie;
- *@optionalargumentvEnd(Number,String,DateObjectornull):themax-ageinseconds(e.g.,31536e3forayear)orthe
- *expiresdateinGMTStringformatorinDateObjectformat;ifnotspecifieditwillexpireattheendofsession;
- *@optionalargumentsPath(Stringornull):e.g.,"/","/mydir";ifnotspecified,defaultstothecurrentpathofthecurrentdocumentlocation;
- *@optionalargumentsDomain(Stringornull):e.g.,"example.com",".example.com"(includesallsubdomains)or"subdomain.example.com";ifnot
- *specified,defaultstothehostportionofthecurrentdocumentlocation;
- *@optionalargumentbSecure(Booleanornull):cookiewillbetransmittedonlyoversecureprotocolashttps;
- *@returnundefined;
- **/
- setItem:function(sKey,sValue,vEnd,sPath,sDomain,bSecure){
- if(!sKey||/^(?:expires|max\-age|path|domain|secure)$/.test(sKey)){return;}
- varsExpires="";
- if(vEnd){
- switch(typeofvEnd){
- case"number":sExpires=";max-age="+vEnd;break;
- case"string":sExpires=";expires="+vEnd;break;
- case"object":if(vEnd.hasOwnProperty("toGMTString")){sExpires=";expires="+vEnd.toGMTString();}break;
- }
- }
- document.cookie=escape(sKey)+"="+escape(sValue)+sExpires+(sDomain?";domain="+sDomain:"")+(sPath?";path="+sPath:"")+(bSecure?";secure":"");
- },
- removeItem:function(sKey){
- if(!sKey||!this.hasItem(sKey)){return;}
- varoExpDate=newDate();
- oExpDate.setDate(oExpDate.getDate()-1);
- document.cookie=escape(sKey)+"=;expires="+oExpDate.toGMTString()+";path=/";
- },
- hasItem:function(sKey){return(newRegExp("(?:^|;\\s*)"+escape(sKey).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=")).test(document.cookie);}
- };
- //docCookies.setItem("test1","Helloworld!");
- //docCookies.setItem("test2","Helloworld!",newDate(2020,5,12));
- //docCookies.setItem("test3","Helloworld!",newDate(2027,2,3),"/blog");
- //docCookies.setItem("test4","Helloworld!","Sun,06Nov202221:43:15GMT");
- //docCookies.setItem("test5","Helloworld!","Tue,06Dec202213:11:07GMT","/home");
- //docCookies.setItem("test6","Helloworld!",150);
- //docCookies.setItem("test7","Helloworld!",245,"/content");
- //docCookies.setItem("test8","Helloworld!",null,null,"example.com");
- //docCookies.setItem("test9","Helloworld!",null,null,null,true);
- //alert(docCookies.getItem("test1"));
源自:https://developer.mozilla.org/en/DOM/document.cookie
Security
It is important to note that thepath
restriction 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.cookie
property). 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.
Specification
See also
- HTTP cookies
- Cookies(Code snippets)