Monday, January 3, 2011

Javascript to add,delete and get browser cookie

//Javascript function to set browser Cookie at client side. The parameters are
c_name :- name of the cookie by which it is identified in browser.
value :- the value of the cookie to set in browser.
expiredays :- number of days to maintain the cookie in browser.

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

//Javascript function to get browser cookie at client side. The parameters are
c_name :- name of the cookie to get from browser.


function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1)
c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}

//Javascript funtion to delete browser cookie. The parameters are
cookie_name :- name of the cookie to be deleted from the browser.

function delete_cookie(cookie_name)
{
var cookie_date = new Date();
cookie_date.setTime(cookie_date.getTime()-1);
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

No comments:

Post a Comment