欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

《JavaScript权威指南》中的一个Cookie工具 博客分类: 前端开发 cookiejavascriptexpiresmax-age 

程序员文章站 2024-03-18 19:07:58
...
《JavaScript权威指南》(第五版)中的一个Cookie工具,但是其中一处代码在IE下有问题,关掉所有IE窗口后cookie value没有保存。

原因是IE6,7,8,9都没有很好的支持max-age属性,所以针对IE使用expires属性代替。

以下是我修改后的代码。

Cookie.js

 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(':');
    for(var i=0;i<a.length;i++){
        this[a[i][0]] = decodeURIComponent(a[i][1]);    
    }
}

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){
        if(window.ActiveXObject){   //update for ie 6,7,8,9
            var nDaysLater = (new Date()).getTime() + (daysToLive*24*60*60*1000);
            cookie += "; expires=" + (new Date(nDaysLater)).toGMTString();
        }
        else
            cookie += "; max-age=" + (daysToLive*24*60*60);
    }
    if(path)    cookie += "; path=" + path;
    if(domain)  cookie += "; domain" + domain;
    if(secure)  cookie += "; secure";
    document.cookie = cookie;
}
Cookie.prototype.remove = function(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.enabled = function(){
    if(navigator.cookieEnabled != undefined)    return navigator.cookieEnabled;
    if(Cookie.enabled.cache != undefined)   return Cookie.enabled.cache;
    if(window.ActiveXObject)    //update for ie 6,7,8,9
        document.cookie = "testcookie=test; expires=" + (new Date((new Date()).getTime() + (10000*1000))).toGMTString();
    else
        document.cookie = "testcookie=test; max-age=10000";
    var cookies = document.cookie;
    if(cookies.indexOf("testcookie=test") == -1){
        return Cookie.enabled.cache = false;
    }else{
        if(window.ActiveXObject)    //update for ie 6,7,8,9
            document.cookie = "testcookie=test; expires=" + (new Date((new Date()).getTime() - (10000*1000))).toGMTString();
        else
            document.cookie = "testcookie=test; max-age=0";
        return Cookie.enabled.cache = true;
    }
}