Wednesday, October 15, 2014

Advanced JavaScript Tutorial 02 - Part 3

Advanced JavaScript Tutorial 02 - Part 3


Reading and Writing Multiple Cookies 

On the last page, we learned how to cram lots of information into one cookie. Another way to do this is with multiple cookies.
Saving multiple cookies is very straightforward. We’ve learned that every cookie has a name. In the last example, we named the cookie my_happy_cookie, and did something like this:
1var the_cookie = "my_happy_cookie=happiness_and_joy";
2 
3document.cookie = the_cookie;
To save multiple cookies, just give each cookie a different name. If you’re adding a new cookie, setting document.cookie doesn’t delete cookies that are already there. So if we do this:
1var the_cookie = "my_happy_cookie=happiness_and_joy";
2 
3document.cookie = the_cookie;
4 
5var another_cookie= "my_other_cookie=more_joy_more_happiness";
6 
7document.cookie = another_cookie;
You’ll now have access to both cookies. It’s sort of weird, so make sure you understand what’s going on.
Let’s assume you executed the last block of code and you want to access my_happy_cookie. If you look at document.cookie, you’ll see this:
1my_happy_cookie=happiness_and_joy;
2 
3my_other_cookie=more_joy_more_happiness;
If you don’t believe me, just look at your cookie.
This is very nice, but it makes reading a specific cookie a bit more difficult. Here’s some (slightly simplified) code that allows you to isolate a specific cookie:
01function WM_readCookie(name) {
02 
03if (document.cookie == '') {
04 
05 
06 
07// there's no cookie, so go no further
08 
09 
10 
11return false;
12 
13else {
14 
15 
16 
17// there is a cookie
18 
19 
20 
21var firstChar, lastChar;
22 
23var theBigCookie = document.cookie;
24 
25firstChar = theBigCookie.indexOf(name);
26 
27 
28 
29// find the start of 'name'
30 
31 
32 
33if(firstChar != -1) {
34 
35 
36 
37// if you found the cookie
38 
39 
40 
41firstChar += name.length + 1;
42 
43 
44 
45// skip 'name' and '='
46 
47 
48 
49lastChar = theBigCookie.indexOf(';', firstChar);
50 
51 
52 
53// Find the end of the value string (i.e. the next ';').
54 
55 
56 
57if(lastChar == -1) lastChar = theBigCookie.length;
58 
59 
60 
61return unescape(theBigCookie.substring(firstChar, lastChar));
62 
63 
64 
65else {
66 
67 
68 
69// If there was no cookie of that name, return false.
70 
71 
72 
73return false;
74 
75}
76 
77 
78 
79}
80 
81 
82 
83}
84 
85 
86 
87// WM_readCookie
Since this is very well commented, I’ll just let you take a look at it and figure out what’s happening on your own (c’mon, you know everything you need to know to make sense of this).
Once you’ve parsed that information, let’s leave our “setting and reading basic cookies” discussion and look at some of the cooler things you can do with cookies.

More About Cookies

So far, you’ve learned how to set and read a basic cookie. Unfortunately, your basic cookie will get deleted automatically when a user quits out of the browser. Sometimes this is for the best. Since each domain, such as webmonkey.com, is allowed only 20 cookies on any user’s machine, you don’t want to waste space with cookies that aren’t saved between browser sessions.
However, if you do want to save cookies on users’ hard drives, you have to set an expiration date, which has to be in a special format called GMT. For example:
1Mon, 27-Apr-1998 00:00:00 GMT
(This is the date on which Koko the gorilla had her AOL chat session.)
Getting the GMT right can be sort of a pain, especially when it comes to figuring out the day of the date. Is it a Monday? A Friday? To make things easier on you, JavaScript has a date method called toGMTString. Here’s an easy way to set an expiration date to some distant time in the future:
1var the_date = new Date("December 31, 2023");
2 
3var the_cookie_date = the_date.toGMTString();
Once you establish an expiration date for your cookie, you have to add this information before you set the cookie. Therefore, your cookie should look like this:
1cookie_name=blah_blah;expires=date
Basically, you’re just adding expires=date to the cookie string and separating the different cookie components with a semicolon.
Here’s how to build a cookie that will last until the end of the Mayan calendar:
01function setCookie()
02 
03{
04 
05 
06 
07// get the information
08 
09 
10 
11//
12 
13 
14 
15var the_name = prompt("What's your name?","");
16 
17var the_date = new Date("December 31, 2023");
18 
19var the_cookie_date = the_date.toGMTString();
20 
21 
22 
23 
24 
25// build and save the cookie
26 
27 
28 
29//
30 
31 
32 
33var the_cookie = "my_cookie=" + escape(the_name);
34 
35the_cookie = the_cookie + ";expires=" + the_cookie_date;
36 
37document.cookie = the_cookie;
38 
39 
40 
41}
At the end of all this, the_cookie will look something like this:
1my_cookie=thau;expires=Fri, 31-Dec-2023 00:00:00 GMT
When this cookie is set, it will live on the user’s hard drive until the expiration date.
The expiration date also allows you to delete cookies you don’t want users to have any more. If you set the expiration date of a cookie to a time that’s already passed, the cookie will be deleted from the cookie file.
In addition to name and expires, there are two other important cookies components that you’ll need to know about: path and domain.

Cookie Path and Domain

This is the last tricky cookies hurdle: By default, a cookie can be read only by HTML pages that sit on the same web server and in the same directory as the page that set the cookie.
For example, if you have a JavaScript on “http://chimp.webmonkey.com/food/bananas/banana_puree.htm” that asks people for their names, you might want to access a given name on another one of your Web pages, such as the homepage (http://chimp.webmonkey.com/.) To allow this, you have to set the “path” of the cookie. The “path” sets the top level directory from which a cookie can be read. Set the path of a cookie to the top-level directory of your Web pages, and the cookie is readable by all your Web pages.
Do this by adding path=/; to your cookie. If you just wanted the cookie readable solely in the “food” directory, you’d add path=/food; to your cookie.
A second hitch is that some Web sites have lots of little domains. For example, Webmonkey might have pages at “chimp.webmonkey.com,” “gorilla.webmonkey.com,” and “ape.webmonkey.com.” By default, if a Web page on “chimp.webmonkey.com” sets a cookie, only pages on “chimp.webmonkey.com” can read it. If we wanted all the machines in the “webmonkey.com” domain to read the cookie, we’d have to add “domain=webmonkey.com” to the cookie. Don’t get clever though. Pages at “republicans.com” can’t set or read cookies from “democrats.com.”
To put all the above together – set a cookie on the Web page “http://chimp.webmonkey.com/food/bananas/banana_puree.htm” that we want to be readable by all Webmonkey pages – we’d have to do this:
01function setCookie()
02 
03{
04 
05var the_name = prompt("What's your name?","");
06 
07var the_cookie = "cookie_puss=" + escape(the_name) + ";" ;
08 
09var the_cookie = the_cookie + "path=/;";
10 
11var the_cookie = the_cookie + "domain=webmonkey.com;";
12 
13document.cookie = the_cookie;
14 
15}
And so ends the cookies lesson. Let’s review what we’ve learned so far and then go onto a final exercise.

Lesson 2 Review

Today was a big day, probably the biggest in this set of lessons. However, the things you learned today take you a significant step closer to the ability to create JavaScripts that are more than just cute. For example, today’s homework assignment is to add a “bookmarks” feature to your do-it-yourself Web browser.
Here are the main topics we covered today:
Advanced String Handling
Including
  • charAt – getting a character at a certain position
  • indexOf – getting the position of a character
  • substring – getting a piece of a string
  • split – splitting a string up into an array
Associative Arrays
Another JavaScript datatype useful for storing things like phone books, password lists, birthdays, and cookie information
Cookies
How to set them, read them, and make them permanent
Tomorrow we’ll cover:
  • Preloading images to speed up image swaps
  • Creating your own objects and a do-it-yourself virtual pet
  • Getting to hard-to-find objects

No comments:

Post a Comment