XHanch Studio Log in | Register | Cart

Forum

Notifications
Clear all

[How to] Set and get/read cookie with JavaScript

1 Posts
1 Users
0 Likes
882 Views
XHanch
(@xhanch-alt)
Posts: 2105
Member Admin
Topic starter
 

Cookies can be created, read and erased by JavaScript. They are accessible through the property document.cookie. Though you can treat document.cookie as if it's a string, it isn't really, and you have only access to the name-value pairs.

Here are two JavaScript functions to set and get cookie:

function set_cookie(name, val, exp, pth, dmn, sec){
var tdy = new Date();
tdy.setTime(tdy.getTime());
if(exp)
exp = exp * 1000 * 60 * 60 * 24;
var dte_exp = new Date(tdy.getTime() + exp);

document.cookie = name + "=" + escape(val) +
(exp?";expire=" + dte_exp.toGMTString():"") +
(pth?";path=" + pth:"") +
(dmn?";domain=" + dmn:"") +
(sec?";secure":"");
}

function get_cookie(chk_nme) {
var lst_cke = document.cookie.split(";");
var tmp_cke = '';
var cke_nme = '';
var cke_val = '';
var cke_fnd = false;

for(var rpi=0;rpi<lst_cke.length;rpi++){
tmp_cke = lst_cke[rpi].split("=");
cke_nme = tmp_cke[0].replace(/^s+|s+$/g, "");
if(cke_nme == chk_nme ){
cke_fnd = true;
if(tmp_cke.length > 1)
cke_val = unescape(tmp_cke[1].replace(/^s+|s+$/g, ""));
return cke_val;
break;
}
tmp_cke = null;
cke_nme = "";
}

if(!cke_fnd)
return null;
}
 
Posted : 19/05/2011 6:13 pm
Share:

× Close Menu