Main Page

Cookies in JavaScript

Cookies in JavaScript
Dealing with cookies in JavaScript is a little complicated because of a notoriously poor interface. The
object has a property called
, which is a single string containing all cookies accessible
by the given page. The
property is also unique in that setting it to a specific value only alters the
cookies available to the page; it doesn’t actually change the value of
itself. This functionality is
part of the BOM and, as such, isn’t guided by any sort of specifications (which explains its lack of logic).
To create a cookie, you must create a string in the following format:
cookie_name=cookie_value; expires=expiration_time; path=domain_path;
domain=domain_name; secure
Only the first part of the string, specifying the name and value, is mandatory to set a cookie; all other
parts are optional. This string is then set to the
property to create the cookie. For
example, to set a simple cookie, use the following:
document.cookie = “name=Nicholas”;
document.cookie = “book=” + encodeURIComponent(“Professional JavaScript”);
Reading the value of
gives access to these cookies, along with all others accessible
from the given page. If you display the value of
after running the two lines of the
previous code, it equals
“name=Nicholas; book=Professional%20JavaScript”
. Even if other
cookie attributes are specified, such as an expiration time,
only returns the name
and value of each cookie with a semicolon separating the cookies.
Because creating and reading cookies requires remembering this format, most developers use functions
to handle the details. The function to create a cookie is the easiest:
function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) {
var sCookie = sName + “=” + encodeURIComponent(sValue);
if (oExpires) {
sCookie += “; expires=” + oExpires.toGMTString();
if (sPath) {
sCookie += “; path=” + sPath;
if (sDomain) {
sCookie += “; domain=” + sDomain;
if (bSecure) {
sCookie += “; secure”;
document.cookie = sCookie;
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 483

JavaScript EditorFree JavaScript Editor     Ajax Editor