A cookie is a variable that is stored on the visitor’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values. Two examples of cookies are cookie name and cookie password. The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like “Welcome to My Computer!” The name is retrieved from the stored cookie. Similarly, the first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie.
Now, consider an example which creates and stores a cookie containing the name of the visitor. Take a look at this code:
1 2 3 4 5 6 7 |
function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } |
The parameters of the function above hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.
Now a function that would return a specified cookie:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } |
The function above makes an array to retrieve cookie names and values, then it checks if the specified cookie exists, and returns the cookie value. JAVA script is the most powerful yet a very simple tool to deal with the process of creation and storing of the cookies and hence is a very handy tool for any web developer.