Manipulating Cookies
A common task in JavaScript is getting and setting cookies in the browser. Cookies allow you to store simple key value pairs of information in the browser in a persistent manner. You can access the cookies by the server-side scripts and JavaScript to determine what those values are.
You can access cookie information using the document.cookie object. This object contains all the cookies in the string format name=value; name=value; ....
Setting a Cookie Value in the Browser
To add a new cookie for your web site, set document.cookie = "name=value; expireDate; path;";. The expire date needs to be a date set using .toGMTString(), and the path is the path on your web site that the cookie applies to.
Getting a Cookie Value from the Browser
To get the value of the cookie, split the document.cookie value using the ; character, and then iterate through the resulting array until you find the name you are looking for.
Example Getting and Setting Cookies
The following code shows a full example of setting and getting cookies. When the code is run, two cookies are set: one for name and the other for language. The cookies are then retrieved from the browser and written to the web page, as shown in Figure 3.2.
01 <html> 02 <head> 03 <title>Python Phrasebook</title> 04 <meta charset="utf-8" /> 05 <script type="text/javascript" 06 src="../js/jquery-2.0.3.min.js"></script> 07 <script> 08 function setCookie(name, value, days) { 09 var date = new Date(); 10 date.setTime(date.getTime()+(days*24*60*60*1000)); 11 var expires = "; expires="+date.toGMTString (); 12 document.cookie = name + "=" + value + 13 expires + "; path=/"; 14 } 15 function getCookie(name) { 16 var cArr = document.cookie.split(';'); 17 for(var i=0;i < cArr.length;i++) { 18 var cookie = cArr[i].split("=",2); 19 cookie[0] = cookie[0].replace(/^\s+/,""); 20 if (cookie[0] == name){ return cookie; } 21 } 22 } 23 setCookie("name", "Brad", 1); 24 setCookie("language", "English", 1); 25 document.write("<h3>Cookies</h3>"); 26 var c1 = getCookie("name"); 27 document.write(c1[0] + " is set to "+ c1[1] +"<br>"); 28 var c2 = getCookie("language"); 29 document.write(c2[0] + " is set to " + c2[1]); 30 </script> 31 </head> 32 <body> 33 </body> 34 </html>
ch0302.html
Figure 3.2 Adding cookie output using JavaScript.