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.
It's not very difficult to create custom cookie-handling code -– after all, all you're really doing is parsing and manipulating a set of values in an encoded string. JavaScript makes it even easier by exposing a "document.cookie" element that does most of the dirty work for you; all you need to do is give it the cookie data to be written. Consider the following example, which illustrates:
<html> <head>
<script language = "JavaScript"> <!-- start hiding function writeCookie() {
// ask for input var name = prompt("What's your name?", "");
// set expiry date var d = new Date("January 31, 2004"); var cd = d.toGMTString();
// set cookie parameters var c = "username=" + escape(name) + ";expires=" + cd;
// write cookie document.cookie = c; }
// stop hiding --> </script>
</head>
<body onLoad="writeCookie()"> </body>
</html>
Most of this is pretty simple: the prompt() method takes care of popping up a box for user input, and the corresponding value is encoded into the cookie string for storage. Similarly, a Date object is instantiated with the cookie's expiry date, converted to the requisite format using the Date object's toGMTString() method and the resulting value is added to the cookie string as part of the expires attribute explained earlier. Once the cookie string is ready, the document.cookie property takes care of writing it to a file.
Now, try running the code above in your browser. You should see an input box. Enter your name into the box. The value you entered into the box should now be saved as a cookie to your hard drive. If you're the suspicious type, verify this by looking in your browser's cookies directory; you should see a cookie with contents like this: