Last Modified:12/9/98
[Previous] [Home] [Next]

Using Cookies in JavaScript


Credit: Mulchaey et al (ST Sci/UMD/NASA)

Cookies in JavaScript

Cookies are relatively small pieces of data that "save state"; that is, they allow you to retrieve information from a previous web session. Cookies have the following characteristics:
  • They are to be used for relatively small amounts of information
  • The number of cookies is very limited, so you should use as few as possible. One way to do this is to compact many values into a single cookie, e.g., if you have name-value pairs you might store then as "name1:value&name2:value&name3:value" where, say, ":" and "&" are used as separators
  • The full syntax of a cookie is:
    [cookie-name]=[cookie-values-list]; expires=[date]
    ; secure; path=[path]; domain=[domain]
    where
    • [cookie-name] is the name you give to the cookie
    • [cookie-values-list] is a compacted list of values
    • [date] is the GMT date in standard form
    • "secure" means that its access is restricted
    • [path] and [domain] control where the cookie can be located with respect to the web page. If both of these are missing you can access the cookie from the directory and subdirectories on the same web sever as your web page. [path] allows you to access cookies from different locations on your server, and [domain] lets you access cookies on different servers.
For the purpose of this class we will ignore the "secure", [path], and [domain] options and so our reduced syntax for cookies is:
...; [cookie-name]=[cookie-values-list]; expires=[date];...

Note that the characters '=' and ';' are reserved and should not be used. Also note that blank spaces in cookies come out looking like '&20', and so you might not want to use them to avoid some confusion. There is a pair of functions in JavaScript named "escape()" and "unescape()" that let you encode troublesome characters in cookies if you need to do so, but all of our examples will use underscores in place of blanks and avoid "=' and ';'.

We illustrate cookies with two examples: the first is a very small program that creates, displays, destroys, and lists cookies and their values. Here is the example .

The second example is a "near-practical" program which keeps track of the money balance for a number of customers based on their purchases and payments. Pay special attention to the string manipulation routines which extract and compact cookie values. Here is the example .


[Previous] [Home] [Next]