本地存儲是HTML5中提出來的概念,分localStorage和sessionStorage。通過本地存儲,web應用程序能夠在用戶瀏覽器中對數據進行本地的存儲。與 cookie 不同,存儲限制要大得多(至少5MB),並且信息不會被傳輸到服務器。
什么時候用本地存儲?
跨期:不同時間打開頁面,比如這次登錄需要用到上次登錄時保存的數據。
跨頁:在同一個瀏覽器打開同域的多個標簽頁,它們之間需要互通數據。
選用哪種存儲方式?
最簡單的數據保存方式就是在js里定義變量並賦值,這不屬於本地存儲的范疇,但大多數情況下這樣做就夠了。
cookie的適用場景:數據量小;數據需要隨http請求傳遞到服務端;存儲有具體時限的數據;低版本瀏覽器,不支持localStorage和sessionStorage時。
localStorage的使用場景:數據大於4k;需要跨標簽頁使用數據;長期存儲數據;
sessionStorage的適用場景:數據只在本次會話有效;數據僅在當前標簽頁有效。sessionStorage對比直接js賦值變量的優勢,是可以在同頁面跨iframe使用。
瀏覽器自身會緩存img、js、css等數據,localStorage也可以起到類似作用。
整理本地存儲方法
基於localStorage制作一個本地存儲插件storage.js,針對只能存字符串、不能設置時限等進行補充,設想:
- 在不支持localStorage時自動使用cookie
- 類型轉換,可存儲數字、布爾、對象等
- 可設置時限,超時就自我刪除
- 附帶整理cookie方法
用法展示:
/** setItem( key, value, time)
* key: 鍵名,字符串
* value:鍵值,可以是Stirng/Boolean/Number/Object等類型
* time: 超時時間,非必填,數字型(單位毫秒)。默認長期有效。
**/
storage.setItem("text", "this is string");
storage.setItem("money", 1234);
storage.setItem("person", {name: "Jone"}, 24*60*60*1000);
// getItem 獲取值
storage.getItem("money"); //返回數字類型的值1234
// removeItem 刪除某數據
storage.removeItem("money");
// clear 清除所有數據
storage.clear();
// 類似方法,操作cookie,只限於存儲字符串
storage.setCookie("mycookie", "this is string", 60*60*24*30);
storage.getCookie("mycookie");
storage.removeCookie("mycookie");
storage.clearCookie();
storage.js :
(function(window) {
var storage = {};
// 是否支持localStorage
if (!window.localStorage) {
storage.support = false;
} else {
storage.support = true;
}
// time為超時時間(單位毫秒),非必填
storage.setItem = function(key, value, time) {
if (this.support) {
if (typeof key != "string") {
console.log("*STORAGE ERROR* key必須是字符串");
return;
}
if (time) {
if (typeof time != "number") {
console.log("*STORAGE ERROR* time必須是數字");
return;
} else {
time = parseInt(time) + (new Date()).getTime();
}
} else {
time = null;
}
var setValue = {
value: JSON.stringify(value),
time: time
}
localStorage.setItem(key, JSON.stringify(setValue));
} else {
storage.setCookie(key, value, time)
}
};
// 不存在的值會返回null
storage.getItem = function(key) {
if (this.support) {
var getValue = JSON.parse(localStorage.getItem(key));
if (!getValue) {
return null;
}
if (getValue.time && getValue.time < (new Date()).getTime()) {
localStorage.removeItem(key);
return null;
} else {
return JSON.parse(getValue.value)
}
} else {
storage.getCookie(key)
}
};
// 移除某個值
storage.removeItem = function(key) {
if (this.support) {
localStorage.removeItem(key);
} else {
storage.removeCookie(key)
}
};
// 清空存儲
storage.clear = function() {
if (this.support) {
localStorage.clear();
} else {
storage.clearCookie();
}
};
/**** cookie方法 ****/
storage.setCookie = function(key, value, time) {
if (typeof key != "string") {
console.log("*STORAGE ERROR* key必須是字符串");
return;
} else {
if (typeof time != "number") {
// cookie默認存365天
time = 365 * 24 * 60 * 60 * 1000;
}
var d = new Date();
d.setTime(d.getTime() + time);
document.cookie = key + "=" + value + "; expires=" + d.toGMTString();
}
};
storage.getCookie = function(key) {
var cookies = document.cookie.split(";")
var cookieValue;
for (var i = 0; i < cookies.length; i++) {
if (key == cookies[i].split("=")[0]) {
cookieValue = cookies[i].split("=")[1];
break;
}
}
return cookieValue;
};
storage.removeCookie = function(key) {
document.cookie = key + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
};
storage.clearCookie = function() {
var cookies = document.cookie.split(";")
for (var i = 0; i < cookies.length; i++) {
document.cookie = cookies[i].split("=")[0] + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
};
window.storage = storage;
})(window)
