首页 > 代码库 > 原生js封装cookie获取、设置及删除

原生js封装cookie获取、设置及删除

使用cookie(key,value,options)

参数key,value,options(可选)

function cookie(key,value,options){
    if(typeof value !== "undefined"){//write
       options=options||{}
       var cookie=encodeURIComponent(key)+"="+encodeURIComponent(value);
    if (typeof options.expries==="number"){
       var date=new Date();
       date.setDate(date.getDate()+options.expries);
       cookie += ";expries="+date.toUTCString();
    }
    if(options.path)
       cookie += ";path="+options.path;
       if(options.domain)
       cookie += ";domain="+options.domain;
    if(options.secure)
       cookie += ";secure";
    document.cookie=cookie;
    }else{//read
    var cookies=document.cookie.split(";");
    for(var i=0;i<cookies.length;i++){
         var cookie=cookies[i].split("=");
            var name=decodeURIComponent(cookie.shift());
         if (name===key)
             return decodeURIComponent(cookie.join("="));
      }
      return null;
    }
}

 

function removeCookie(key,options){//remove
    options=options||{};
    options.expries=-1;
    cookie(key,"",options);
}

 

  

原生js封装cookie获取、设置及删除