In this article, find out how to store and retrieve persistent data with cookies, small files that allow you to do big things. This article explains the basics of cookies, demonstrates reading and writing them in JavaScript, and illustrates their use in a real-world application.
Now, that takes care of writing a cookie. But how about reading back the data you stored in it?
Fortunately, the Bill Dortch library has you covered on that front as well, with its GetCookie() function. To illustrate, consider the following example, which checks for a cookie and retrieves a value from it for display if available:
Here, when the page loads, the GetCookie() function will check to see if a cookie named "username" exists on the client for the specified domain/path combination. If it does, it will be retrieved, the value stored within it will be read, and an alert box will be shown with a welcome message.
Let's look at another example, this one tracking the number of visits that the user has made to the particular Web page:
// check to see if cookie exists // if not, this is first visit if(GetCookie("visits") == null) { var visitCount = 1 } // else this is second or greater visit // retrieve last counted value and add 1 else { visitCount = parseInt(GetCookie("visits"))+1 }
// set expiry date for 1 year from now var d = new Date(); d.setDate(d.getDate() + 365);
// update cookie with new count SetCookie("visits", visitCount, d);
Here, as before, I use an if test to check whether a cookie already exists to track the number of visits. If it does, I use the GetCookie() function to retrieve the value; if it does not, I assume this is the first visit to the page and initialize the counter to 1. The value of the counter is then updated (if necessary) and written back to the cookie in readiness for the next visit.