You are here: irt.org | FAQ | JavaScript | Cookie | Q1014 [ previous next ]
Store a named cookie on your computer - with any data in it:
<SCRIPT LANGUAGE="JavaScript"><!-- function Set_Cookie(name,value,expires,path,domain,secure) { document.cookie = name + "=" +escape(value) + ( (expires) ? ";expires=" + expires.toGMTString() : "") + ( (path) ? ";path=" + path : "") + ( (domain) ? ";domain=" + domain : "") + ( (secure) ? ";secure" : ""); } var today = new Date(); var zero_date = new Date(0,0,0); today.setTime(today.getTime() - zero_date.getTime()); var todays_date = new Date(today.getYear(),today.getMonth(),today.getDate(),0,0,0); var expires_date = new Date(todays_date.getTime() + (52 * 7 * 86400000)); // 52 weeks var name = ''; var value = 'myCookieValue'; Set_Cookie(name,value,expires_date); //--></SCRIPT>
then in your page, check for your named cookie:
<SCRIPT LANGUAGE="JavaScript"><!-- function Get_Cookie(name) { var start = document.cookie.indexOf(name+"="); var len = start+name.length+1; if ((!start) && (name != document.cookie.substring(0,name.length))) return null; if (start == -1) return null; var end = document.cookie.indexOf(";",len); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(len,end)); } if (Get_Cookie('myCookieName')) { // cookie found so not update counter } else { document.write('<IMG SRC="/cgi-bin/counter.pl" WIDTH="1" HEIGHT="1">'); } //--></SCRIPT>
The following was submitted by Gerard Pinzone:
When I used this example to create a cookie in IE, the the expiration year was 2072! The code didn't work properly in Netscape. I suspect NS thought it was 1972. Anyway, I checked out other people's approaches to cookies and the calculation of the current and expiration date were a lot simpler. I got the code to work when I did the following:
var today = new Date(); //var zero_date = new Date(0,0,0); //today.setTime(today.getTime() - zero_date.getTime()); //var todays_date = new Date(today.getYear(),today.getMonth(),today.getDate(),0,0,0); var todays_date = new Date(today.getTime()); var expires_date = new Date(todays_date.getTime() + (52 * 7 * 86400000)); // 52 weeks
I tested all this with NS 4.7, IE 4.01, and IE 5.5. I didn't regression test with older browsers.