↑
Main Page
setCookie
The
setCookie()
function systematically builds up a cookie string based on the arguments passed in.
Only the first two arguments are required, so the function checks to make sure that each argument exists
before it’s added to the cookie string. The third argument is expected to be a
Date
object so the
toGMTString()
method can be called. At the end of the function, the
document.cookie
is set with
the cookie string. This function is used as follows:
setCookie(“name”, “Nicholas”);
setCookie(“book”, “Professional JavaScript”, new Date(Date.parse(“Jan 1, 2006”)));
setCookie(“message”, “Hello World! “, new Date(Date.parse(“Jan 1, 2006”)),
“/books”, “http://www.wrox.com”, true);
The next function,
getCookie()
, retrieves the value of a cookie when the name is passed in:
function getCookie(sName) {
var sRE = “(?:; )?” + sName + “=([^;]*);?”;
var oRE = new RegExp(sRE);
if (oRE.test(document.cookie)) {
return decodeURIComponent(RegExp[“$1”]);
} else {
return null;
}
}
This function uses a regular expression built out of the name of the cookie. Regular expressions are the
easiest way to extract a particular value from
document.cookie
because of the cookie string format. If
there’s only one cookie, then the string is a simple name and value pair, and the value is all the characters
after the equal sign up to the end of the string. If more cookies follow, they are separated by semicolons.
This means that the value for any cookie (other than the last one) comprises all characters after the equal
sign but before the next semicolon. The regular expression makes it easy to take all this into account, set-
ting up a capturing group to retrieve the cookie value. You can then get the values of cookies like so:
var sName = getCookie(“name”);
var sBook = getCookie(“book”);
var sMessage = getCookie(“message”);
The last function is
deleteCookie()
, which immediately removes a cookie from the system. As men-
tioned previously, setting its expiration time to a past date can accomplish this. In order have this work,
however, the path and domain information must be the same as when you created the cookie, so these
must also be arguments:
function deleteCookie(sName, sPath, sDomain) {
setCookie(sName, “”, new Date(0), sPath, sDomain);
}
Because
setCookie()
sets all the same information as
deleteCookie()
, it makes sense just to use it
and pass in an expiration date that already occurred (in this case, January 1, 1970).
Using these functions, it’s easy to manipulate cookies using JavaScript. Even if the server creates cookies,
JavaScript can still read them, which is where the real power lies.
484
Chapter 16
19_579088 ch16.qxd 3/28/05 11:42 AM Page 484
Free JavaScript Editor
Ajax Editor
©
→