Cookie
// 获取文件
var MyCookie = {
get: function get(name) {
var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
var arr = document.cookie.match(reg);
return arr ? decodeURIComponent(decodeURI((arr[2]))) : null;
},
/**
* @param expires {Number} cookie的过期时间,存入时开始后的第几天
*/
set: function set(name, value, expires = 30){
var exp = new Date();
exp.setTime(exp.getTime() + expires * 24 * 60 * 60 * 1000);
document.cookie = name + '=' + encodeURIComponent(encodeURI(value)) + ';expires=' + exp.toGMTString();
},
del: function del(name){
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var value = getCookie(name);
if (value != null) {
document.cookie = name + '=' + value + ';expires=' + exp.toGMTString();
}
}
};
·
localStorage
var MyLocalStorage = {
/**
* 总容量5M
* 存入缓存,支持字符串类型、json对象的存储
* 页面关闭后依然有效 ie7+都有效
* @param key 缓存key
* @param value
* @time 数字 缓存有效时间(秒) 默认1200s
* 注:localStorage 方法存储的数据没有时间限制。第二天、第二周或下一年之后,数据依然可用。不能控制缓存时间,故此扩展
* */
set: function set(key, value, time) {
if (!localStorage) {
return false;
}
if (!time || isNaN(time)) {
time = 1200;
}
try {
var expireDate = (new Date() - 1) + time * 1000;
localStorage.setItem(key, JSON.stringify({val: value, exp: expireDate}));
} catch (e) {
}
return true;
},
get: function get(key) {
try {
if (!localStorage) {
return null;
}
var value = localStorage.getItem(key);
var result = JSON.parse(value);
var now = new Date() - 1;
if (!result) {
return null;
}// 缓存不存在
if (now > result.exp) { // 缓存过期
this.del(key);
return null;
}
return result.val;
} catch (e) {
this.del(key);
return null;
}
},
del: function del(key) {
if (!localStorage) {
return false;
}
localStorage.removeItem(key);
return true;
},
// 清空所有缓存
delAll: function delAll(){
if (!localStorage) {
return false;
}
localStorage.clear();
return true;
}
}
·
SessionStorage
var MySessionStorage = {
set: function set(key, vaule) {
if (!sessionStorage) {
return false;
}
try {
switch (typeof vaule) {
case 'object':
vaule = JSON.stringify(vaule);
break;
}
sessionStorage.setItem(key, vaule);
} catch (e) {
}
return true;
},
// **获取缓存*/
get: function get(key) {
try {
if (!sessionStorage) {
return null
}
var cacheValue = sessionStorage.getItem(key);
var result = JSON.parse(cacheValue);
if (typeof result == 'object' && result) {
} else {
result = cacheValue;
}
return result;
} catch (e) {
this.del(key);
return null;
}
},
/**
* 移除缓存,一般情况不手动调用,缓存过期自动调用
* @param key
* @returns {boolean}
*/
del: function del(key) {
if (!sessionStorage) {
return false;
}
sessionStorage.removeItem(key);
return true;
},
// 清空所有缓存
delAll: function delAll() {
if (!sessionStorage) {
return false;
}
sessionStorage.clear();
return true;
}
}