All About Cookies
Why cookie? The original name for a cookie came from the term “magic cookie”—a token passed between two programs. Though accessible from JavaScript, cookies aren’t really script-based: they’re a mechanism of the HTTP server. As such, they’re accessible by both the client and the server.
Whatever the name, cookies are small key-value pairs associated with an expiration date and with a domain/path, both of which are meant to ensure that the right cookies are read by the right servers. The information they contain is transmitted as part of the web-page request, and thus the data is available to the server and to the browser.
Storing and Reading Cookies
Cookies are accessible, like most other browser elements, through the document object. To create a cookie, you’ll need to provide a cookie name, or key, an associated value, a date when it expires, and a path associated with the cookie. To access it, you’ll access the document cookie and then have to parse the cookie out.
Luckily there’s a plethora of cookie functions out and about. To get a better idea of how they work, I’ll provide a variation of functions for setting, getting, and erasing a cookie and explain what happens with each step in the process.
To create a cookie, just assign the document cookie value a string with the following format:
cookieName=cookieValue; expirationdate; path
The cookie name and value are whatever you want and need, as long as the value is a simple value. I’ve used cookie names starting with ...
Get Learning JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.