
38
|
JavaScript Pocket Reference
even when the user quits the browser, add an expiration date
using a string of the form:
name=value; expires=date
The expiration date should be in the form returned by Date.
toGMTString()
. If you want the cookie to be accessible to
other documents from your web site, you can specify a path
prefix:
name=value; expires=date; path=prefix
A single document may have more than one cookie associ-
ated with it. To query a document’s cookies, simply read the
value of the
cookie property. This string contains name=value
strings separated from each other by a semicolon and a
space. When reading cookies, you’ll never see a “path=” or
“expires=” clause; you’ll just get the cookie name and value.
Here’s a function that retrieves the value of a single named
cookie from the
cookie property. It assumes that cookie val-
ues never contain semicolons.
function getCookie(name) {
// Split cookies into an array
var cookies = document.cookie.split('; ');
for(var i = 0; i < cookies.length; i++) {
var c = cookies[i]; // One cookie
var pos = c.indexOf('='); // Find = sign
var n = c.substring(0,pos); // Get name
if (n == name) // If it matches
return c.substring(pos+1); // Return value
}
return null; // Can't find the named cookie
}
The W3C DOM
The W3C DOM standardizes most of the features of the leg-
acy DOM, but also adds important new ones. In addition to
supporting
forms[], images[], and other