// 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>
<body onLoad="writeCookie()"> </body>
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: