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.
In your travels across the Web, I'm sure you've experienced Web sites that seem to know you only too well, displaying your name and email address when you visit them and (in some cases) even remembering the pages you visited the last time you were there. Before you allow your paranoia full rein, though, let me tell you that you probably provided the information yourself to the site in some previous visit, and what you see when you return is merely the results of your own actions, reprocessed for a better visitor experience.
So how do they do it? Well, most of these sites save personal information, such as your name and email address, in files on your hard drive, and read these files every time you re-visit the site. These files are known as cookies, and they're a simple and easy way to add personalization features to your site. Cookies can also be used to record information about your activities on a particular site; however, they can only be read by the site that created them.
If you have a Web site which caters to a large number of visitors, think of how beneficial similar technology could be to you. You could recognize frequent visitors and greet them by name, "remember" the pages they browsed on their last visit and pop up recommendations for similar content, personalize their experience so that they see your Web site in their favourite colours or layout...the possibilities are endless. And over the course of this article, I'm going to get you started down this particular road, by showing you how to read and write cookies using JavaScript, my favourite language for client-side scripting.