If you have any better insights, please discuss them!
/*
* Js Class Cookie
* Author:Mr Co
*/
var Cookie = function(/*Cookie name*/name){
this.$name = name;
var allcookies = document.cookie;
if(allcookies == '') return;
var cookies = allcookies.split(';');
var cookie = null;
for(var i = 0; i < cookies.length; i ){
if(cookies[i].substring(0,name.length 1) == (name '=')){
cookie = cookies[i];
break;
}
}
if(cookie == null) return;
var cookieval = cookie.substring(name.length 1);
var a = cookieval.split('&');
for(var i = 0; i < a.length; i ){
a[i] = a[i].split(':');
}
for(var i = 0; i < a.length; i ){
this[a[i][0]] = decodeURIComponent(a[i][1]);
}
}
/*
* Save Cookie data object
*/
Cookie.prototype.store = function(/*Expiration time (1 means one day and so on)*/daysToLive,/*Current Cookie effective address*/path, /*Current cookie valid domain name access*/domain,/*security*/secure){
var cookieval = '';
for(var prop in this){
if((prop.charAt( 0) == '$') || ((typeof this[prop]) == 'function')) continue;
if(cookieval != '') cookieval = '&';
cookieval = prop ':' encodeURIComponent(this[prop]);
}
var cookie = this.$name '=' cookieval;
if(daysToLive || daysToLive == 0){
cookie = ' ; max-age=' (daysToLive * 24 *60 *60);
}
if(path) cookie = '; path=' path;
if(domain) cookie = ';domain=' domain;
if(secure) cookie = ';secure';
document.cookie = cookie;
}
/*
* Remove the specified attribute of the Cookie data object
*/
Cookie.prototype.remove = function(/*Current Cookie valid address*/path,/*Current Cookie valid domain name access*/domain,/*Security*/secure){
for(var prop in this ){
if(prop.charAt(0) != '$' && typeof this[prop] != 'function') delete this[prop];
}
this.store(0,path ,domain,secure);
}
/*
* Verify whether the current client browser supports Cookies
*/
Cookie.IsAllowCookie = function(){
if(! navigator.cookieEnabled){
alert('Warm reminder:
n Your browser currently has disabled page cookies! This may cause you to
nrnWhen you select food data, refresh the page and lose the food data you have selected! rnrnIt is recommended that you enable browser cookies!');
return false;
}
return true;
}
Test JS DEMO
function testFn(){
var cookie = new Cookie('Test');
if(!cookie.name || !cookie.color){
cookie.name = prompt('What is your name:','');
cookie.color = prompt('What is your favorite color:','');
}
if(!cookie.visits) cookie.visits = 1;
else cookie.visits ;
cookie.store(10);
alert('color:' cookie.color ' name:' cookie.name ' visits:' cookie.visits);
}