|
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
Note that the characters '=' and ';' are reserved and normally 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, and some of our examples will demonstrate its use, where
others use underscores in place
of blanks and avoid "=' and ';'.
We illustrate cookies with three 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 .
The third example shows how you can trace the movements of a user as they
navigate your web pages. This is sometimes used to determine if a
web page is confusing: if a person mouses back and forth over
elements many times, it may indicate that the layout and wording need to be
clarified. This
example
also illustrates
- how you can maintain continuity across multiple web pages
- how you can track user-interactions with different HTML elements
- how you can interface cookie information with Perl CGI scripts
which run on the server.
And here is the text of the
CGI
program that handles the cookie information
|
|
 |
|
 |