|
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 ';'.
Cookies are actually stored on the PC where the browser is invoked.
In Windows 95/98
they reside in the directory C:\Windows\Cookies .
In Windows XP they may reside in other places on the "C:" drive but
if you search for the file name Cookies you will find them.
Here is a very small
example of a program that creates, displays, destroys, and lists
cookies and their values
|
|
 |
|
 |