Previous Page
Next Page

Using Cookies as Counters

Because cookies are persistent, that is, because they are available across multiple sessions between a Web server and browser, you can use cookies to store how many times a particular user has accessed a page. But this isn't the same thing as the page counters you see on many Web pages. Because a cookie is specific to a user, you can only tell that user how many times he or she has visited; you can't use cookies to tell all users how many times the page has been hit. Still, it's useful to know how to create such an individual counter, and you can adapt Script 10.6 for other purposes, too (see Tips).

Script 10.6. This script counts your cookies.

window.onload = initPage;

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

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

     document.cookie = "pageHit=" + hitCt + ";expires=" + expireDate.toGMTString();
     document.getElementById("pageHits"). innerHTML = "You have visited this page " + 
hitCt + " times.";
}

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 use a cookie as a counter:

1.
var expireDate = new Date();
expireDate.setMonth(expireDate. getMonth()+6);



These two lines are the same as in steps 7 and 8 of the "Baking Your First Cookie" example. Refer there for an explanation.

2.
var hitCt = parseInt(cookieVal ("pageHit"));



The string pageHit is the name of the cookie. In a few steps, you'll see the function cookieVal(). This line takes the name of the cookie from cookieVal(), turns it into a number using the parseInt() method, and then stores the result in the variable hitCt. The parseInt() method changes a string (which is what is in the cookie) into a number (which is what the variable needs to use it as a counter).

3.
hitCt++;



Now take the value of hitCt and add 1 to it, incrementing the counter.

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



This writes back the updated information to the cookie for future use. What's being written is a text string that combines the string "pageHit=" with the incremented value of hitCt and adds ";expires=" with the expiration date, which was incremented by six months back in step 1.

5.
document.getElementById("pageHits"). innerHTML = "You have visited this page " + hitCt + "
 times.";



This line displays the user message in the document (Figure 10.5). There are extra spaces after "page" and before "times" to make the line look right on screen.

Figure 10.5. Hard to believe we've visited this dull page this often.


6.
function cookieVal(cookieName) {



This line begins a new function called cookieVal(). It is passed some data, which can then be referenced inside the function as the variable cookieName.

7.
var thisCookie = document.cookie. split("; ");



The variable thisCookie is set to the array generated by the split("; ") method.

8.
for (var i=0; i<thisCookie.length; i++) {



Here we're beginning a loop, just as in step 4 of the "Showing Your Cookies" example.

9.
if (cookieName == thisCookie[i]. split("=")[0]) {



This conditional checks to see if cookieName is the same as the ith element of the cookie array.

10.
return thisCookie[i].split("=")[1];



If the test in step 9 succeeded, then return the cookie's value.

11.
return 0;



If we've looked at all the items in the array and found no match, return a 0 value.

Tips

  • When you load the HTML page that calls this script, press the Reload button in your browser to see the counter increment.

  • As mentioned earlier, you can adapt Script 10.6 for other purposes. One possibility would be to use a cookie to track when a particular user had last visited your site and display different pages depending on when that was. For example, some online magazines have a cover page with artwork and the names of the stories in the day's issue. If the user visits the site more than once in a 24-hour period, they only see the cover page the first time; subsequent visits jump the user directly to the site's Table of Contents page.

  • If you want a true page hit counter, one that tells how many times a page has been loaded by all users, you'll need to use a counter program that is installed on your Web server. Check with your Web hosting company to see if they have counters available, or put "Web page hit counter" into your favorite search engine.



Previous Page
Next Page