HTML DOM Document cookie
Example
Get all cookies associated with this document:
Description
The cookie property sets or returns a semicolon-separated list of key=value pairs (document cookies).
An example of creating a cookie:
Note
Cookies cannot contain commas, semicolons or whitespaces.
The encodeURIComponent() Method ensures they don't.
See Also:
Advice:
Somtimes the Storage API is a better tool:
Syntax
Return the cookie:
Set the cookie:
Parameter
A semicolon-separated list of name=value pairs, followed with any of thise optional values:expires=date
A date in GMT format (Use the Date.toUTCString method).
Default value: The cookie is deleted when the browser is closed.
max-age=seconds
The max age before the cookie is deleted.
If to 0 or a date in the past, the cookie is deleted.
path=path
An absoulute path to the directory the cookie belongs to ('/dir').
Default value: Current directory.
domain=domainname
The domain of the site ('example.com').
Default value: The domain of the document.
secure
Use a secure protocol (https) for sending the cookie to the server.
Return Value
Cookies vs Local Storage
Cookies are for client-server (browser-server) applications.
Local storage are for client (browser) applications.
Cookies are associated with websites. If the data is for client use, sending cookies in every HTTP header is waste of bandwith.
Some users have cookies disabled as a rule in their browsers.
A Cookie has a size limit of 4 Kilobytes. Local Storage has a limit of 5 Megabytes per domain.
A Cookie have expiration date. Local Storage has not.
Browser Support
document.cookie is a DOM Level 2 (2001) feature.
It is fully supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera | IE |
| Yes | Yes | Yes | Yes | Yes | 9-11 |