Previous Page
Next Page

Handling Multiple Cookies

You will often want to deal with more than one cookie at a time, and Script 10.8 shows you how to read from more than one cookie and display the information. This example shares a fair amount of code with the "Using Cookies as Counters" example.

Script 10.8. Use an array to deal with multiple cookies in a single script.

window.onload = initPage;

function initPage() {
     var now = new Date();
     var expireDate = new Date();
     expireDate.setMonth(expireDate.getMonth()+6);

     var hitCt = parseInt(cookieVal("pageHit"));
     hitCt++;

     var lastVisit = cookieVal("pageVisit");
     if (lastVisit == 0) {
        lastVisit = "";
     }

     document.cookie = "pageHit=" + hitCt + ";expires=" + expireDate.toGMTString();
     document.cookie = "pageVisit=" + now + ";expires=" + expireDate.toGMTString();

     var outMsg = "You have visited this page " + hitCt + " times.";
     if (lastVisit != "") {
        outMsg += "<br />Your last visit was " + lastVisit;
     }
     document.getElementById("cookieData"). innerHTML = outMsg;
}

function cookieVal(cookieName) {
     var thisCookie = document.cookie.split("; ");

     for (var i=0; i<thisCookie.length; i++) {
        if (cookieName == thisCookie[i]. split("=")[0]) {
           return thisCookie[i].split("=")[1];
        }
     }
     return 0;
}

To handle multiple cookies:

1.
var lastVisit = cookieVal ("pageVisit");



We start off by looking for a cookie named pageVisit by passing that string to the cookieVal() function. It returns a value, which is then stored in lastVisit.

2.
if (lastVisit == 0) {
  lastVisit = "";
}



If the value of lastVisit is zero, then put a null value into lastVisit. We now know the user has never been here before.

3.
document.cookie = "pageHit=" + hitCt + ";expires=" + expireDate.toGMTString();
document.cookie = "pageVisit=" + now + ";expires=" + expireDate.toGMTString();



These two lines write the two cookies back to disk with an updated hit number and visit date.

4.
var outMsg = "You have visited this page " + hitCt + " times.";
if (lastVisit != "") {
  outMsg += "<br />Your last visit was " + lastVisit;
}



The outMsg variable stores the outgoing message to our site's visitor and starts off by being set to tell them how many times they've been here. The next lines check if the user has been here before (in code: if lastVisit isn't null) and if they have, we remind them when.

5.
document.getElementById ("cookieData").innerHTML = outMsg;



And finally, outMsg is displayed on the screen, telling the user what they've done before. The result of this script is shown in Figure 10.8.

Figure 10.8. The two cookies, written to the screen (along with some other text).



Previous Page
Next Page