Advanced JavaScript Tutorial Lesson 02 Part 2
Cookie Introduction
Now that you’ve mastered advanced string handling and associative arrays, it’s time to open up the cookie jar. As I mentioned earlier, cookies are little bits of information that you can leave on a user’s hard drive, where they stay even after the user leaves your site or turns off the computer, which is extremely useful when you want to remember information about repeat visitors.
Let’s look at a basic example of a working cookie. In this example, we set a cookie on one page and then read it from another page. As you play around with the example, try to think about how you would do this without cookies. Here’s the very basic example of a working cookie.
Had your fill of cookie dough tasting? Let’s move on to the next step of the recipe.
More About Cookies
Because cookies involve writing to, and reading from, users’ hard drives, security issues arise that the people who wrote Netscape, MSIE, and the other cookie-friendly browsers had to confront. The most important limitations for this tutorial are:
- Not everyone has a cookie-friendly browser (but most do).
- Not everyone who has a cookie-friendly browser will accept your cookies (but most will).
- Each domain is allotted only 20 cookies, so use them sparingly.
- Cookies must be no larger than 4 KB. That’s just over 4,000 characters, which is plenty.
With those limitations in mind, let’s learn about setting cookies.
Setting Cookies
Setting a basic cookie is very easy. All you have to do is create a string in the form of cookie_name=value
and then set the document.cookie
property to that. The only trick:cookie values must never have spaces, commas, or semicolons. Happily, you don’t really have to worry about this because a pair of functions will code and decode your properties:they are escape()
and unescape()
.
Our simple example, which stored your name as a cookie, looks like this:
01
function
setCookie()
02
03
{
04
05
var
the_name = prompt(
"What's your name?"
,
""
);
06
07
08
09
var
the_cookie =
"wm_javascript="
+ escape(
"username:"
+ the_name);
10
11
12
13
document.cookie = the_cookie;
14
15
16
17
alert(
"Thanks, now go to the next page."
);
18
19
20
21
}
The middle two lines of this function are the critical ones:
var the_cookie = "wm_javascript=" + escape("username:" + the_name);
- If I entered “dave thau” at the prompt, this line would create a string that looks like
wm_javascript=username%3Adave%20thau
. This means that I’m going to save a cookie named wm_javascript
to the hard drive. That cookie is going to have the value username%3Adave%20thau
– the escape() function replaced the colon after username with %3A
and the space between “dave” and “thau” with a %20
.When we read the cookie, we’re going to look for the cookie named wm_javascript
, then grab the username%3Adave%20thau
, unescape() it, which changes the %3A
back to a colon and the %20
back into a space, and then chop off the username:
.
document.cookie = the_cookie;
- And this sets the cookie. Easy, huh?
Now let’s learn how to read cookies.
cookie_name=value
and then set the document.cookie
property to that. The only trick:cookie values must never have spaces, commas, or semicolons. Happily, you don’t really have to worry about this because a pair of functions will code and decode your properties:they are escape()
and unescape()
.01 | function setCookie() |
02 |
03 | { |
04 |
05 | var the_name = prompt( "What's your name?" , "" ); |
06 |
07 |
08 |
09 | var the_cookie = "wm_javascript=" + escape( "username:" + the_name); |
10 |
11 |
12 |
13 | document.cookie = the_cookie; |
14 |
15 |
16 |
17 | alert( "Thanks, now go to the next page." ); |
18 |
19 |
20 |
21 | } |
var the_cookie = "wm_javascript=" + escape("username:" + the_name);
wm_javascript=username%3Adave%20thau
. This means that I’m going to save a cookie named wm_javascript
to the hard drive. That cookie is going to have the value username%3Adave%20thau
– the escape() function replaced the colon after username with %3A
and the space between “dave” and “thau” with a %20
.When we read the cookie, we’re going to look for the cookie named wm_javascript
, then grab the username%3Adave%20thau
, unescape() it, which changes the %3A
back to a colon and the %20
back into a space, and then chop off the username:
.document.cookie = the_cookie;
Reading Cookies
Once you save a cookie to someone’s hard disk, it’s easy to read. Here’s the code that reads the example cookie:
01
function
readCookie()
02
03
{
04
05
var
the_cookie = document.cookie;
06
07
var
the_cookie = unescape(the_cookie);
08
09
var
broken_cookie = the_cookie.split(
":"
);
10
11
var
the_name = broken_cookie[1];
12
13
alert(
"Your name is:"
+ the_name);
14
15
}
The first line is the important one. Whenever your browser opens a Web page, it calls in whatever cookies it can, then loads them into the document.cookie
property.
The tricky part about reading cookies is getting the information you want out of them. Remember, the cookie we set looks like this:wm_javascript=username%3Adave%20thau
. Everything after the first line of the function is devoted to pulling the username out of the cookie. Here’s a breakdown of that process:
var the_cookie = unescape(the_cookie);
- Undo the stuff that the escape() function created. In this case, unescape() swaps the
%3A
with a colon, and the %20
with a space.
var broken_cookie = the_cookie.split(":");
- Split the cookie into two parts at the colon.
var the_name = broken_cookie[1];
- Grab the part after the colon, which is dave thau.
alert("Your name is:" + the_name);
- Yee-haw!
This example used a cookie that only stored one bit of information:the username. As I said before, cookies can store up to 4 KB, which leaves plenty of room for quite a bit more information.
01 | function readCookie() |
02 |
03 | { |
04 |
05 | var the_cookie = document.cookie; |
06 |
07 | var the_cookie = unescape(the_cookie); |
08 |
09 | var broken_cookie = the_cookie.split( ":" ); |
10 |
11 | var the_name = broken_cookie[1]; |
12 |
13 | alert( "Your name is:" + the_name); |
14 |
15 | } |
document.cookie
property.wm_javascript=username%3Adave%20thau
. Everything after the first line of the function is devoted to pulling the username out of the cookie. Here’s a breakdown of that process:var the_cookie = unescape(the_cookie);
%3A
with a colon, and the %20
with a space.var broken_cookie = the_cookie.split(":");
var the_name = broken_cookie[1];
alert("Your name is:" + the_name);
Complicated Cookie Reading
If you want your cookie to contain more than just one piece of information, you can make the value of the cookie as long as you want (up to the 4000 character limit). Say you’re looking to store a person’s name, age, and phone number. You do something like this:
1
var
the_cookie =
"username:thau/age:older than the hills/phone:411"
;
2
3
document.cookie=
"my_happy_cookie="
+ escape(the_cookie);
I use a slash to separate property names and a colon to distinguish the property name from the property value. The slash and colon are arbitrary choices – they could be anything, like say, this:
1
var
the_cookie =
"username=thau&age=older than the hills&phone=411"
;
2
3
document.cookie=
"my_happy_cookie="
+ escape(the_cookie);
The delimiters you choose are up to you. Just remember what you used so you can decode the cookie later.
As with our simple example, the easy part is setting the cookie. Things get a little sticky, however, when it comes to pulling the information out of the cookie when you need it. I suggest using associative arrays to store all the information. For example, let’s say you saved this to someone’s hard drive:
1
my_happy_cookie=username:thau/age:older than the hills/phone:411
You could put the information into a handy associative array like this:
01
function
readTheCookie(the_info)
02
03
{
04
05
// load the cookie into a variable and unescape it
06
07
08
09
var
the_cookie = document.cookie;
10
11
var
the_cookie = unescape(the_cookie);
12
13
14
15
// separate the values from the cookie name
16
17
18
19
var
broken_cookie = the_cookie.split(
"="
);
20
21
var
the_values = broken_cookie[1];
22
23
24
25
// break each name:value pair into an array
26
27
28
29
var
separated_values = the_values.split(
"/"
);
30
31
32
33
// loop through the list of name:values and load
34
35
// up the associate array
36
37
38
39
var
property_value =
""
;
40
41
42
43
for
(
var
loop = 0; loop < separated_values.length; loop++)
44
45
46
47
{
48
49
property_value = separated_values[loop];
50
51
var
broken_info = property_value.split(
":"
);
52
53
var
the_property = broken_info[0];
54
55
var
the_value = broken_info[1];
56
57
the_info[the_property] = the_value;
58
59
}
60
61
62
63
}
If you had this function in your JavaScript, you could call it like this:
1
var
cookie_information =
new
Array();
2
3
readTheCookie(cookie_information);
And then you’d have cookie_information["username"], cookie_information["age"],
and cookie_information["phone"]
set correctly.
This may look a little funky, but actually it’s not that hard. Here’s a step-by-step analysis of what’s going on:
var the_cookie = document.cookie;
- This is the easy part. It puts the cookie into a variable.
var the_cookie = unescape(the_cookie);
- Undo the work of escape().
var broken_cookie = the_cookie.split("=");
var the_values = broken_cookie[1];
- These lines make
the_values
equal to username:thau/age:older than the hills/phone:411
.
var separated_values = the_values.split("/");
- This makes an array called
separated_values
that contains three elements:separated_values[0] = "username:thau"
separated_values[1] = "age:older than the hills"
separated_values[2] = "phone:411"
for (loop = 0; loop < separated_values.length; loop++)
- This loops through the three elements of
separated_values
.
property_value = separated_values[loop];
- This grabs the current
name:value pair
, the first one being username:thau
.
var broken_info = property_value.split(":");
- This breaks the pair into two elements into an array called
broken_info
where broken_info[0] = "username"
broken_info[1] = "thau"
var the_property = broken_info[0];
- The first time through the loop,
the_property
will be “username”
var the_value = broken_info[1];
the_value
will be “thau.”
the_info[the_property] = the_value;
- Here’s where associative arrays come in handy. This makes
the_info["username"] = "thau"
. So now, when you want the username from the cookie, you can just say something like var the_name = the_info["username"];
.
- And so on
- Each time through the loop, a new element gets added to
the_info
. At the end of the loop is the_info["username"] = "thau", the_info["age"] = "old as the hills"
and the_info["phone"] = 411
.
It is a bit cumbersome, but it’s the way I prefer to get large quantities of information in and out of cookies. There are lots of ways to do it, and if you find another way that you like, all the power to you.
Okay, the last thing you need to know is what to do when you’re dishing out multiple cookies.
1 | var the_cookie = "username:thau/age:older than the hills/phone:411" ; |
2 |
3 | document.cookie= "my_happy_cookie=" + escape(the_cookie); |
1 | var the_cookie = "username=thau&age=older than the hills&phone=411" ; |
2 |
3 | document.cookie= "my_happy_cookie=" + escape(the_cookie); |
The delimiters you choose are up to you. Just remember what you used so you can decode the cookie later.
As with our simple example, the easy part is setting the cookie. Things get a little sticky, however, when it comes to pulling the information out of the cookie when you need it. I suggest using associative arrays to store all the information. For example, let’s say you saved this to someone’s hard drive:
1 | my_happy_cookie=username:thau/age:older than the hills/phone:411 |
01 | function readTheCookie(the_info) |
02 |
03 | { |
04 |
05 | // load the cookie into a variable and unescape it |
06 |
07 |
08 |
09 | var the_cookie = document.cookie; |
10 |
11 | var the_cookie = unescape(the_cookie); |
12 |
13 |
14 |
15 | // separate the values from the cookie name |
16 |
17 |
18 |
19 | var broken_cookie = the_cookie.split( "=" ); |
20 |
21 | var the_values = broken_cookie[1]; |
22 |
23 |
24 |
25 | // break each name:value pair into an array |
26 |
27 |
28 |
29 | var separated_values = the_values.split( "/" ); |
30 |
31 |
32 |
33 | // loop through the list of name:values and load |
34 |
35 | // up the associate array |
36 |
37 |
38 |
39 | var property_value = "" ; |
40 |
41 |
42 |
43 | for ( var loop = 0; loop < separated_values.length; loop++) |
44 |
45 |
46 |
47 | { |
48 |
49 | property_value = separated_values[loop]; |
50 |
51 | var broken_info = property_value.split( ":" ); |
52 |
53 | var the_property = broken_info[0]; |
54 |
55 | var the_value = broken_info[1]; |
56 |
57 | the_info[the_property] = the_value; |
58 |
59 | } |
60 |
61 |
62 |
63 | } |
1 | var cookie_information = new Array(); |
2 |
3 | readTheCookie(cookie_information); |
cookie_information["username"], cookie_information["age"],
and cookie_information["phone"]
set correctly.This may look a little funky, but actually it’s not that hard. Here’s a step-by-step analysis of what’s going on:
var the_cookie = document.cookie;
var the_cookie = unescape(the_cookie);
var broken_cookie = the_cookie.split("=");
var the_values = broken_cookie[1];
the_values
equal to username:thau/age:older than the hills/phone:411
.var separated_values = the_values.split("/");
separated_values
that contains three elements:separated_values[0] = "username:thau"
separated_values[1] = "age:older than the hills"
separated_values[2] = "phone:411"
for (loop = 0; loop < separated_values.length; loop++)
separated_values
.property_value = separated_values[loop];
name:value pair
, the first one being username:thau
.var broken_info = property_value.split(":");
broken_info
where broken_info[0] = "username"
broken_info[1] = "thau"
var the_property = broken_info[0];
the_property
will be “username”var the_value = broken_info[1];
the_value
will be “thau.”the_info[the_property] = the_value;
the_info["username"] = "thau"
. So now, when you want the username from the cookie, you can just say something like var the_name = the_info["username"];
.the_info
. At the end of the loop is the_info["username"] = "thau", the_info["age"] = "old as the hills"
and the_info["phone"] = 411
.
No comments:
Post a Comment