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

时间:2022-09-04 21:11:50

使用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);
}