Home »

Javascript and Cookie

Here is the way to create, retrieve and delete cookies using JavaScript.

Overview of Cookies

Cookie is a small text file used to store information about a user visiting your site. This file is stored on their computer by the browser. In this file you can store user's customized data, login information or something like that.

To view cookies with IE: Run -> shell:cookies
To view cookies with FF: Tools/Options/ On the Privacy Tab, select Show Cookie
...

Set Cookie

Here is the javascript function to create cookie.
function setCookie(name, value, expires) {
 document.cookie = name + "=" + escape(value) 
 + ((expires == null) ? "" : "; expires=" + expires) 
 + "; path=/";
}
name: name of the cookie, you will use this name to get the cookie.
value: data, information that you want to save.
expires: time when cookie will expire (it will be deleted from the user's computer).
expires variable here is not a datetime object, I suggest using a string here!
You can do as follow:
var now = new Date();
 now.setTime(now.getTime() + 1000 * 60 * 60); //expiration time is one hour
 //if you want to set it to one day, change to: 1000 * 60 * 60 * 24
 
    var exp = now.toUTCString();
    setCookie("yourCookieName", "yourCookieValue", exp);

Get Cookie

function getCookie(name) {
 var dc = document.cookie;
 var cname = name + "=";

 if (dc.length > 0) {
  begin = dc.indexOf(cname);
  if (begin != -1) {
   begin += cname.length;
   end = dc.indexOf(";", begin);
   if (end == -1) end = dc.length;
    return unescape(dc.substring(begin, end));
  }
 }
 return null;
}

Delete Cookie

The way to delete cookie is to set its expiration time to now a time before now
function delCookie(name) {
 var now = new Date();           
 now.setFullYear(2000, 01, 01);
 var exp = now.toUTCString();
 
 setCookie(name, "", exp);
}

Hope this entry help you!
If you found any mistake or error in this entry, please let me know. I'll try to fix that a.s.a.p.
Any solution is highly appreciated!

-Share2Learn-

No comments:

Post a Comment