JavaScript Cookie 工具类

来源:互联网 发布:淘宝人群标签在哪里 编辑:程序博客网 时间:2024/05/02 02:03
function Cookie(name){    this.$name=name;//Remember the name of this cookie    var allCookies=document.cookie; //Get a list of all  cookies pertain to this document    if(allCookies == "") return;//If there are no cookies, we don't have anything to do.    var cookies=allCookies.split(";");//Break the string of all cookies into individual cookie strings    var cookie=null;    for(var i=0;i<cookies.length;i++){//Loop through the cookie strings, looking for our name        if(cookies[i].substring(0,name.length+1)==(name+'=')){//Does this cookie string begin with the name we want?            cookie=cookies[i];break;        }    }    if(cookie==null) return;//If we didn't find a matching cookie, quit now    var cookieValue=cookie.substring(name.length+1);//Get the cookie value    var a=cookieValue.split('&');//Break the cookie value into an array of name/value pairs    for(var i=0;i<a.length;i++){//Break each pair into an array        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 cookieValue='';    for(var prop in this){//Loop through the Cookie object and put together the value of the cookie        if((prop.charAt(0)=='

) || (typeof this[prop])=='function'){continue;} if(cookieValue!='') cookieValue +='&'; cookieValue += prop + ':' +encodeURIComponent(this[prop]); } var cookie=this.$name+'='+cookieValue; 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;}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(window.navigator.cookieEnabled != undefined) return window.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; }}

	
				
		
原创粉丝点击