This blog is moved to
http://amalhashim.wordpress.com

Wednesday, March 10, 2010

Cookie manipulation through JavaScript

<script type="text/javascript">
currentuser = "amal"
window.onload=function() {
if (navigator.cookieEnabled) {
var username = readCookie("username");
if (username) {
alert("cookie name = " + username);
if (username != currentuser) {
eraseCookie(username);
} else {
setCookie("username",username);
}
} else {
alert("setting cookie");
setCookie("username", currentuser);
}
}
}

// set cookie expiration date in year 2010
function setCookie(key,value) {
var cookieDate = new Date(2010,11,10,19,30,30);
document.cookie=key + "=" + encodeURI(value) + "; expires=" +
cookieDate.toGMTString() + "; path=/";
}

// each cookie separated by semicolon;
function readCookie(key) {
var cookie = document.cookie;
var first = cookie.indexOf(key+"=");

// cookie exists
if (first >= 0) {
var str = cookie.substring(first,cookie.length);
var last = str.indexOf(";");

// if last cookie
if (last < 0) last = str.length;

// get cookie value
str = str.substring(0,last).split("=");
return decodeURI(str[1]);
} else {
return null;
}
}

// set cookie date to the past to erase
function eraseCookie (key) {
var cookieDate = new Date(2000,11,10,19,30,30);
document.cookie=key + "= ; expires="+cookieDate.toGMTString()+"; path=/";
}

</script>

No comments: