JavaScript 对 cookie的操作

Author : luckyGirl

cookie概述,介绍了cookie的属性优劣势,这一篇以实际代码来展示如何在JavaScript中进行操作,主要操作包括存储,读取,删除,以及测试cookie是否被禁用。

<script type=”text/javascript”>
// Cookie 工具类
function Cookie(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(‘:’);
this[a[i][0]]=decodeURIComponent(a[i][1]);
}
}
// 存储cookie
Cookie.prototype.store=function(daysTolive,path,domain,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*60*60*24);
}
if(path){
cookie += ‘; path=’ + path;
}
if(domain){
cookie += ‘; domain=’ + domain;
}
if(secure){
cookie += ‘; secure=’ + secure;
}
};
//删除cookie
Cookie.prototype.remove=function(daysTolive,path,domain,secure){
for(var prop in this){
if(prop.charAt(0) != ‘$’ && typeof this[prop] !=’function’){
delete this[prop];
}
}
this.store(0,path,domain,secure);
};
// 判断cookie是否可用
Cookie.enabled = function(){
if(navigator.cookieEnabled !=undefined){
return navigator.cookieEnabled;
}
if(Cookie.enabled.cache != undefined){
return Cookie.enabled.cache;
}
document.cookie = ‘testcookie = test;max-age=10000’;
var cookies = document.cookie;
if(cookies.indexOf(‘testcookie’) == -1){
return Cookie.enabled.cache = false;
}else{
document.cookie = ‘testcookie = test;max-age=0’;
return Cookie.enabled.cache = true;
}
};
// 使用实例
var cookie = new Cookie(‘vistordata’);
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);
document.write(‘<h1 style=”color:’ + cookie.color + ‘”>’ +
‘Welcome, ‘ + cookie.name + ‘!’ + ‘</h1>’ +
‘<p>You have visited ‘ + cookie.visits + ‘ times.’ + 
‘<button onclick=”window.cookie.remove();”>Forget Me</button>’);
</script>
 
参考资料: 《JavaScript权威指南》
standard

Have your say