原生 JavaScript 設定瀏覽器快取及cookie
阿新 • • 發佈:2018-12-30
//設定快取
function set_cache(key,value){
if(key=='') return false;
localStorage.setItem(key, value);
}
//讀取快取
function get_cache(key){
return localStorage.getItem(key);
}
//刪除快取
function remove_cache(key){
localStorage.removeItem(key);
}
//寫入cookie
function setCookie(name,value){
var Days = 30;
var exp = new Date();
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
//獲取cookie
function getCookie(name){
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg) )
return unescape(arr[2]);
else
return null;
}
//刪除cookie
function delCookie(name){
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null)
document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}