工作中常用到的cookie和localStore存储方法
// Cookie 存储
CookieStore = {
get: function (name) {
var cookieName = encodeURIComponent(name) + "=",
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = null;
if (cookieStart > -1) {
var cookieEnd = document.cookie.indexOf(";", cookieStart)
if (cookieEnd == -1) {
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
}
return cookieValue;
},
set: function (name, value, expires, path, domain, secure) {
var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
if (expires instanceof Date) {
cookieText += "; expires=" + expires.toGMTString();
}
if (path) {
cookieText += "; path=" + path;
}
if (domain) {
cookieText += "; domain=" + domain;
}
if (secure) {
cookieText += "; secure";
}
document.cookie = cookieText;
},
unset: function (name, path, domain, secure) {
this.set(name, "", new Date(0), path, domain, secure);
}
}
// 本地存储
LocalStore = {
set: function (n, val) {
if (window.localStorage && localStorage.setItem) {
try {
// safari 隐私浏览器会报错
localStorage.setItem(n, val);
} catch (e) {
Utils.cookieStore.set(n, val);
}
} else {
Utils.cookieStore.set(n, val);
}
return this;
},
get: function (n) {
if (window.localStorage && localStorage.getItem) {
try {
return localStorage.getItem(n);
} catch (e) {
return Utils.cookieStore.get(n);
}
} else {
return Utils.cookieStore.get(n);
}
},
remove: function (n) {
if (window.localStorage && localStorage.removeItem) {
try {
localStorage.removeItem(n);
} catch (e) {
Utils.cookieStore.unset(n);
}
} else {
Utils.cookieStore.unset(n);
}
return this;
}
}
cookie存储和localStorage 存储有什么区别呢?
1. cookie在浏览器和服务器间来回传递,localStorage 仅在本地保存。
2. cookie数据和loaclstore存储大小限制也不同,cookie数据不能超过4k,而localStorage 可以达到5M或更大。
3. 数据有效期不同,localStorage:始终有效,窗口或浏览器关闭也一直保存,因此用作持久数据;cookie只在设置的cookie过期时间之前一直有效,即使窗口或浏览器关闭。
4. 作用域不同,localStorage 在所有同源窗口中都是共享的,cookie也是在所有同源窗口中都是共享的。