240
Part III Integrating JavaScript into Design
A cookie is typically just a text file—that’s the easiest and most convenient way to think of it.
A cookie can contain several different elements, but at heart it is a set of name/value pairs,
many of which are set by the site operator or developer and are optional.
When visitors come to my website, http://www.braingia.org/, and go to the blog link, they
might end up with a cookie on their computer. The contents of the cookie would be something like this:
Name: cookie4blog
Content: sess_id02934235
Domain: www.braingia.org
Path: /
Send For: Any type of connection
Expires: Never
The browser stores the cookie on the visitor’s computer until the cookie expires, which in this
case is never. When a repeat visitor returns to a site, the visitor’s browser sends the cookie to
the server. The server can then tell that the visitor was there before, and the server may use
some personalized settings from the cookie to customize the visitor’s experience.
One of the features of cookies is that they are sent only to servers on the domain for which
they were set. So, the cookie shown in the preceding code is sent by the browser to a server
only when the domain that the browser is trying to visit matches www.braingia.org. Also, a
cookie can have its secure flag set (the one in the example does not). If the secure flag is set,
the cookie can be sent only over a Secure Sockets Layer (SSL)–enabled session, such as over a
Hypertext Transfer Protocol Secure (HTTPS) connection.
Note Third-party cookies and the subtle ways someone can work around the domain limitation
are beyond the scope of this book.
JavaScript can both create and read cookies. The remainder of this chapter looks at both
functions.
Creating Cookies with JavaScript
You can use JavaScript to create cookies by using the document.cookie property. This section
discusses how to create cookies and send them to the site visitor’s browser.
Tip When working with cookies, using simple string values is important. Avoid spaces, punctuation, and other nonalphanumeric characters, because they are not allowed. You can use these
illegal characters in cookies, but not in their native form—you must escape them, otherwise,
they might cause problems for the cookie, the page, and the browser. Like other problems with
JavaScript and web programming in general, these problems might be subtle and generally difficult to troubleshoot. When in doubt, stick to alphanumeric characters.
Chapter 12 Creating and Consuming Cookies
241
Looking at a Simple Cookie
A cookie needs a name. This bit of JavaScript creates a cookie and then sends it to the
browser:
var cookName = "testcookie";
var cookVal = "testvalue";
var myCookie = cookName + "=" + cookVal;
document.cookie = myCookie;
When you visit a page with the preceding JavaScript code, the code sets a cookie named
testcookie in your browser. Assuming that you allow the cookie, the browser stores the
cookie’s data (testvalue) as well as other information about the cookie for future use.
When you set a cookie through JavaScript, the cookie gets appended to the end of any existing cookies. This process will make more sense when you start reading cookies. You should
also understand that to specify attributes in a particular cookie, you must concatenate the
attribute’s name/value pair onto the cookie as you build it. The next example helps you
to visualize this aspect of working with cookies in JavaScript.
Setting a Cookie’s Expiration Date
The example shown earlier created a cookie by building a name/value pair, like so:
var myCookie = cookName + "=" + cookVal;
In essence, the code looks like this (this cookie has only the cookie name and cookie
data set):
testcookie=testvalue;
To add an expiration date, you add an expires attribute, so the cookie becomes:
testcookie=testvalue; expires=Sat, 12 Mar 2011 17aad:51:50 GMT;
Adding an expiration date is just a matter of concatenating the expiration date onto the end
of the cookie to be sent. The format of the expiration date is important. To get the date formatted correctly for the cookie, you need a few different JavaScript functions. In the following exercise, you practice creating a cookie with an expiration date.
Prior to beginning the exercise, it’s a good idea to enable prompting for cookies in your
browser. Doing so makes debugging much easier, because each time a server or some
JavaScript code sends a cookie to your browser, you get prompted.
Unfortunately, enabling prompting in Windows Internet Explorer is unreliable, so you need
to use Firefox for this exercise. In the Windows version of Firefox, click Tools and then Options
(in the Linux version of Firefox, click Edit and then Preferences). In the Options dialog box,
242
Part III Integrating JavaScript into Design
click the Privacy icon, and then select Use Custom Settings For History from the drop-down
list. Now select Ask Me Every Time from the Keep Until drop-down list, as shown in Figure
12-1.
Figure 12-1 Changing cookie settings in Firefox.
Tip Don’t forget to change these settings back to your normal settings when you’re finished
testing cookie-related issues. The constant prompting can get quite annoying, because of the
number of cookies that most websites set.
Adding an expiration date to a cookie
1. Using Microsoft Visual Studio, Eclipse, or another editor, edit the file cookie-expire.htm
in the Chapter12 sample files folder in the companion content.
2. Within the webpage, add the code in boldface type, shown here (the code is in cookieexpire.txt, and the completed version in cookie.htm—both in the companion content):
"http://www.w3.org/TR/html4/strict.dtd">
Chapter 12 Creating and Consuming Cookies
243
Hello CookieHello
3. Deploy this page to a server and view it in a web browser. You should receive a prompt
like this:
Click Deny in Firefox to make sure this cookie does not get saved by the browser. If
you accidentally accept the cookie, close your browser and reopen it. Because this was
a session cookie, it’ll be closed when you close the browser. Congratulations—you’ve
used JavaScript code to send a cookie to the browser!
4. Modify the code to add lines for the date. This code should appear prior to the
myCookie variable declaration, like this:
var date = new Date();
date.setTime(date.getTime()+604800000)
var expireDate = date.toGMTString();
5. Modify the myCookie variable declaration to include the new expiration elements:
var myCookie = cookName + "=" + cookVal + ";expires=" + expireDate;
6. The entire code should now look like this (the added lines are shown in boldface type):
"http://www.w3.org/TR/html4/strict.dtd">
Hello CookieHello
7. When viewed in a web browser, the JavaScript code on the page sends a cookie to the
browser with an expiration date of exactly one week from the time of your visit. The
dialog box you see looks like the following screenshot. Click the Show Details button to
expand the dialog box so that it looks like this, if necessary:
In this exercise, four lines were added or modified to allow the cookie to have an expiration
date rather than exist only for the life of the active browser window. The first three lines set
the date. The first line creates a new date and places it in the date variable. Next, the code
sets the date using the setTime() method. The parameter for the setTime() method is an expression that includes a call to getTime(). The getTime() method retrieves the current date
in milliseconds since 1/1/1970. The value returned by getTime() represents the current date,
so for the cookie to expire at some point in the future (a week in this case), you calculate the
number of seconds in a week (604,800 to be exact) and then multiply that by 1,000 to convert the time to milliseconds. Add the resulting number (604,800,000) to the value returned
by getTime(). Then, you can convert this number to a Greenwich Mean Time (GMT) string
with the help of the date object’s toGMTString() method.
Finally, the code appends the expires attribute to the cookie. The final result looks like this:
testcookie=testvalue;expires=Mon, 12 Jul 2010 23:22:22 GMT
Chapter 12 Creating and Consuming Cookies
245
Setting the Cookie Path
In the examples shown so far, on my test machine, the browser sends the cookie to the server
when the path for the HTTP request matches /jsbs/c12/, because the server is where I’ve been
serving the pages from for my environment. This path will probably be different in other
cases, such as in your environment or on your test machine. You can change this path by
adding another option onto the cookie when it’s set. A more common scenario is just to set
the path to a forward slash (/) so that the cookie is available for all requests from the originating domain.
Like the expires option, setting the path involves appending a name/value pair to the cookie.
Here’s an example webpage like the ones shown so far in this chapter, which includes the
previously added code to specify an expiration date and the new path option (shown in
boldface type and in the cookie-path.htm file in the companion content):
"http://www.w3.org/TR/html4/strict.dtd">
Hello CookieHello
The preceding code added one line for the path functionality and changed the myCookie
variable definition, adding the new path variable. With this new code, the resulting cookie
now looks like this:
testcookie=testvalue;expires=Mon, 12 Jul 2010 23:22:22 GMT;path=/
View the page that creates this cookie, and you see the cookie dialog box similar to Figure
12-2.
246
Part III Integrating JavaScript into Design
Figure 12-2 Setting the path within the cookie.
Setting the Cookie Domain
The examples shown so far haven’t set a domain attribute; domain is by default set to the
host and domain for the server that is sending the cookie to the browser (or for the server
that sent the JavaScript code responsible for serving the cookie). In these examples, the domain has been www.braingia.org. However, many sites (including braingia.org) have multiple
hosts from which HTTP content is served. For example, there might be an entirely separate server, maybe called images.braingia.org, that serves only the images on the pages in
braingia.org. It would be convenient if you could simply set the domain to braingia.org so
that the same cookies could be shared across the entire domain.
If you think that setting the domain for the cookie is just like setting the path, you’re right.
Appending the domain option to the cookie causes the domain to be set to a specific value.
Here’s an example webpage that integrates the path, expiration date, and now the domain.
The new code to specify the domain and append the domain attribute to the myCookie variable is shown in boldface type (and is located in the cookie-domain.htm file in the companion
content):
"http://www.w3.org/TR/html4/strict.dtd">
Hello CookieHello
When you view the page in a browser, the dialog box, shown in Figure 12-3, appears.
Figure 12-3 Setting the cookie’s domain so that it can be read from anywhere in the braingia.org domain.
Tip Just as you can make the domain less specific (as in this example), you can also make it more
specific, which allows you to create cookies that might be read only by images.braingia.org or by
someotherspecificcomputer.braingia.org. However, you cannot set a domain outside the domain
from which the content is being served. For example, you can’t change the domain value to
microsoft.com for a cookie served from braingia.org. The browser will just ignore it.
Working with Secure Cookies
Setting the secure flag in a cookie indicates that the cookie will be sent only when the
connection uses SSL, such as an HTTPS connection.
The code to add the secure flag onto the myCookie variable you’ve used throughout this
chapter looks like this:
var myCookie = cookName + "=" + cookVal + ";expires=" + expireDate + path + domain +
";secure";
When you view this page in a browser, even over an unencrypted HTTP connection, the
JavaScript code creates the cookie, as indicated in the dialog box shown in Figure 12-4.
Notice that the Send For option value is now "Encrypted connections only", whereas in all
the previous screenshots in this chapter, the value was set to "Any type of connection".
Download from Wow! eBook
248
Part III Integrating JavaScript into Design
Figure 12-4 Setting a cookie’s secure flag.
At this point, you know everything you need to know about setting cookies with JavaScript.
It’s finally time to learn how to read cookies with JavaScript.
Reading Cookies with JavaScript
Until now, you’ve looked at code that sends a cookie to the browser when you visit a webpage. When the browser subsequently visits a page whose domain and path match cookies
stored on the client computer, the browser sends any matching cookies to the server along
with the request for the webpage. The cookie is available to the JavaScript code in the page
when the page is delivered to the browser.
Reading cookies with JavaScript involves taking the cookies from the document.cookie
object and then splitting them into manageable pieces. A call to the split method of
document.cookie takes care of it, because cookies are delimited by semicolons, similar to
the way in which a cookie’s attributes are delimited (as described in the previous section
of the chapter). Here’s an example:
var incCookies = document.cookie.split(";");
With this bit of JavaScript, all the cookies would be split up, waiting to be accessed. With the
help of a for loop, you can loop through all the cookies available for the domain to find each
cookie’s name and data, as follows. (Note that this code does not examine the attributes of
each cookie other than the cookie name and cookie data.)
"http://www.w3.org/TR/html4/strict.dtd">
Reading Cookie
Hello
This code (available in readcookie.htm) reads the available cookies for the domain into a variable called incCookies. The cookies are split at their semicolon delimiters. For example, I set
several cookies for the braingia.org domain, both through my normal use of the site and for
the examples in this chapter. You can read all the cookies for the domain using the preceding
code. Figure 12-5 and Figure 12-6 show two of the alerts.
Figure 12-5 The first cookie read by the loop.
Figure 12-6 The second cookie read by the loop.
Using the for loop, you can split the cookies along the equal sign (=) to further divide the
cookie name from the cookie data, as shown in this code:
var incCookies = document.cookie.split(";");
var cookLength = incCookies.length
for (var c = 0; c < cookLength; c++) {
var pairs = incCookies[c].split("=");
var cookieName = pairs[0];
var cookieValue = pairs[1];
alert("Name: " + cookieName + " - " + "Value: " + cookieValue);
}
In this code (in the readcookie2.htm file in the companion content), each cookie, incCookie[c],
is split at the equal sign (=) and placed into a variable called pairs. The first index of the pairs
variable is the name of the cookie; the second index is its data. Take a look at Figure 12-7 for
an example of the output.
250
Part III Integrating JavaScript into Design
Figure 12-7 Splitting a name/value pair to separate the cookie name and cookie data.
Removing Cookies
There’s no built-in method for removing or deleting cookies, either through JavaScript or
by any other means. To remove a cookie, simply clear its value and set its expiration date
to some time in the past.
A previous example used this code to create and set a cookie:
var cookName = "testcookie";
var cookVal = "testvalue";
var date = new Date();
date.setTime(date.getTime()+604800000)
var expireDate = date.toGMTString();
var path = ";path=/";
var domain = ";domain=braingia.org";
var myCookie = cookName + "=" + cookVal + ";expires=" + expireDate + path + domain;
document.cookie = myCookie;
You can delete this cookie by setting its expiration date to sometime in the past. Note that
the components, such as name, path, and domain, must match for the cookie to be reset. In
effect, you want to overwrite the existing cookie with a new one that expired in the past, as
follows:
var cookName = "testcookie";
var cookVal = "";
var date = new Date();
date.setTime(date.getTime()-60)
var expireDate = date.toGMTString();
var path = ";path=/";
var domain = ";domain=braingia.org";
var myCookie = cookName + "=" + cookVal + ";expires=" + expireDate + path + domain;
document.cookie = myCookie;
This code (in the cookie-delete.htm file in the companion content) causes the testcookie data
to be set to an empty value and the expiration date to be set in the past.
Note When this JavaScript executes, Firefox deletes the cookie immediately; however, other
browsers may keep the cookie until the browser closes.