Chapter 19. Cookies and Client-Side Persistence

The Document object has a property named cookie that was not discussed in Chapter 15. On the surface, this property appears to be a simple string value; however, the cookie property is much more than this: it enables JavaScript code to persistently store data to the user’s hard disk and to retrieve data that was previously stored in this way. Client-side persistence is an easy way to give web applications a memory: a web site can store user preferences so that they can be used again when the user revisits the page, for example.

Cookies are also used for server-side scripting and are a standard extension to the HTTP protocol. All modern web browsers support them and allow them to be scripted with the Document.cookie property. There are other client-side persistence mechanisms that are more powerful but less standard than cookies, and I discuss them briefly at the end of this chapter.

An Overview of Cookies

A cookie is a small amount of named data stored by the web browser and associated with a particular web page or web site.[*] Cookies serve to give the web browser a memory so that scripts and server-side programs can use data that was input on one page on another page, or so the browser can recall user preferences or other state variables when the user leaves a page and then returns. Cookies were originally designed for server-side programming, and at the lowest level, they are implemented as an extension to the HTTP protocol. ...

Get JavaScript: The Definitive Guide, 5th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.