Cookie set, delete, get value and create
/*
JavaScript Application Cookbook
By Jerry Bradenbaugh
Publisher: O'Reilly
Series: Cookbooks
ISBN: 1-56592-577-7
*/
<HTML>
<HEAD>
<TITLE>cookie set, delete, get value and create</TITLE>
<SCRIPT LANUAGE="JavaScript">
// cookies.js
// Derived from the Bill Dortch code at http://www.hidaho.com/cookies/cookie.txt
var today = new Date();
var expiry = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) { endstr = document.cookie.length; }
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal (j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function DeleteCookie (name,path,domain) {
if (GetCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR=WHITE>
<SCRIPT LANGUAGE="JavaScript">
<!--
if (GetCookie('user_id') == null) {
var getName = prompt('Hi... First time, huh?? We all have to through it. Please enter your name.', '');
document.writeln('<H2>Welcome, ' + (getName != '' ? getName : 'Anonymous user') + '</H2>' +
'This is your first visit.');
SetCookie('user_id', (getName != '' ? getName : 'Anonymous user'), expiry);
SetCookie('hit_count', '2', expiry);
}
else {
var getName = GetCookie('user_id');
var getHits = GetCookie('hit_count');
document.writeln('<H2>Welcome Back, ' + getName + '</H2>' +
'You have visited ' + getHits + ' times.');
getHits = parseInt(getHits) + 1;
SetCookie('hit_count', '' + getHits + '', expiry);
}
//-->
</SCRIPT>
</BODY>
</HTML>
Related examples in the same category