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.- See Date.toUTCString() for help formatting this value.
;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).
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)) { return null; }
- return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
- },
- /**
- * docCookies.setItem(sKey, sValue, vEnd, sPath, sDomain, bSecure)
- *
- * @argument sKey (String): the name of the cookie;
- * @argument sValue (String): the value of the cookie;
- * @optional argument vEnd (Number, String, Date Object or null): the max-age in seconds (e.g., 31536e3 for a year) or the
- * expires date in GMTString format or in Date Object format; if not specified it will expire at the end of session;
- * @optional argument sPath (String or null): e.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location;
- * @optional argument sDomain (String or null): e.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com"; if not
- * specified, defaults to the host portion of the current document location;
- * @optional argument bSecure (Boolean or null): cookie will be transmitted only over secure protocol as https;
- * @return undefined;
- **/
- setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
- if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }
- var sExpires = "";
- if (vEnd) {
- switch (typeof vEnd) {
- 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; }
- var oExpDate = new Date();
- oExpDate.setDate(oExpDate.getDate() - 1);
- document.cookie = escape(sKey) + "=; expires=" + oExpDate.toGMTString() + "; path=/";
- },
- hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }
- };
- // docCookies.setItem("test1", "Hello world!");
- // docCookies.setItem("test2", "Hello world!", new Date(2020, 5, 12));
- // docCookies.setItem("test3", "Hello world!", new Date(2027, 2, 3), "/blog");
- // docCookies.setItem("test4", "Hello world!", "Sun, 06 Nov 2022 21:43:15 GMT");
- // docCookies.setItem("test5", "Hello world!", "Tue, 06 Dec 2022 13:11:07 GMT", "/home");
- // docCookies.setItem("test6", "Hello world!", 150);
- // docCookies.setItem("test7", "Hello world!", 245, "/content");
- // docCookies.setItem("test8", "Hello world!", null, null, "example.com");
- // docCookies.setItem("test9", "Hello world!", null, null, null, true);
- // 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.
Specification
See also
- HTTP cookies
- Cookies (Code snippets)