In the Browser
It isn't really related to its parent object, in this case the document object.
Although it's singular in name, it holds all the visible cookies—but it's not an array.
- If you set the cookie property, its new value won't always match what you set it to.
The property's contents (it's a string) doesn't even look complete—what's going on? An example value:
bookmark1=face.htm; my_id=541263; quote=Et%20tu,%20Brutus
<FORM> tag. When you set the
'cookie' property, your data is handed to the browser's cookie management software. When you read the
'cookie' property, you get a report in a single string of the cookies that are currently visible and unexpired for the current window's domain and path. Only name and value attributes are supplied in this report.
This means that when looking for a specific cookie, you must pick the
'cookie' property's string apart. You can't know when a cookie expires or will be visible without explicitly re-setting it. When setting a cookie, you must use a string in a specific format. That format is:
[name]=[value]; expires=[date]; path=[directory]; domain=[domain-name]; secure
The items in brackets are supplied by you—leave the brackets themselves out. Each semi-colon separated item is optional, except the first. The '
[value]' part must be run through the
escape() function first. The date for
'expires' requires the exact format that the
toGMTString() method of the Date object produces:
// example date: 'Mon, 13 Oct 1997 12:40:34 GMT'
Managing cookie strings can be maddening because of the way they work with
document.cookie. Fortunately Bill Dortch solved much of the problem for everyone. This URL
GetCookie() routines that do most of the hard work. The URL can easily be converted into a .
In CGI Programs
Sometimes CGI programs are responsible for a URL's content. A CGI program is called at the end of a URL request, so it can read the cookies that the browser reports. A CGI program also produces the URL response, so it can set cookies that the browser will remember.
DOS file, is intended as a CGI program, and shows cookie reading and writing:
'Set-cookie' shows a new cookie being sent to the browser, called
'test_name'. The format for this line is usually the same as that written to the
'document.cookie' property (see above). The line containing
'getenv' shows the CGI program reading the cookie information sent by the browser. The web server puts it in an environment variable, usually in the same format as is read from the
'Date:' header line. If cookie headers are added with an expiry date, the
'Date:' header tells the browser what the time was in the CGI program when the expiry was set. This helps the browser avoid becoming confused about when the cookie should expire.
Because of differences between Web servers, the CGI headers in this example may need subtle changes for a specific server even though the style shown here is quite standard.