瀏覽器提供的 localStorage 與 sessionStorage 用起来很顺手,但在一些老項目或者有特殊需求的場景下,我們反而必須回到 Cookie。本文分享一個思路:把 Cookie 包裝成和 Storage 一樣的 API,讓讀寫屬性的方式保持直覺。
構造函數接收兩個參數:maxage 表示保存期限(秒),path 表示 Cookie 的作用路徑。實例化時先把 document.cookie 這一整串文本解析成一個「名/值」對象,後續的讀取都走這個對象;寫入時則同時更新內存對象和瀏覽器裡的 Cookie,保證兩邊一致。
為了對齊 Storage 的習慣,對外暴露 length、key(n)、getItem、setItem、removeItem、clear 這幾個成員。
/**
* CookieStorage.js
* 提供與 localStorage / sessionStorage 一致的 API,
* 底層則由 HTTP Cookie 實現。
*/
function CookieStorage(maxage, path) {
// 兩個參數分別代表保存有效期與作用域路徑
// 把 document.cookie 解析成一個對象
var cookies = (function () {
var cookies = {};
var all = document.cookie;
if (all === "") return cookies; // 沒有任何 Cookie,直接返回空對象
var list = all.split("; "); // 按 "; " 拆成名值對
for (var i = 0; i < list.length; i++) {
var cookie = list[i];
var p = cookie.indexOf("="); // 找到第一個等號
var name = cookie.substring(0, p); // 名字
var value = cookie.substring(p + 1);// 值
value = decodeURIComponent(value); // 解碼
cookies[name] = value;
}
return cookies;
}());
// 把所有 Cookie 名收集到數組中,方便按下標訪問
var keys = [];
for (var key in cookies) keys.push(key);
// 對外 API
this.length = keys.length; // Cookie 數量
// 返回第 n 個 Cookie 的名字,越界返回 null
this.key = function (n) {
if (n < 0 || n >= keys.length) return null;
return keys[n];
};
// 讀取值,不存在返回 null
this.getItem = function (name) {
return cookies[name] || null;
};
// 寫入值
this.setItem = function (key, value) {
if (!(key in cookies)) {
keys.push(key);
this.length++;
}
cookies[key] = value;
// 值需要編碼後才能安全寫入
var cookie = key + "=" + encodeURIComponent(value);
if (maxage) cookie += "; max-age=" + maxage;
if (path) cookie += "; path=" + path;
document.cookie = cookie;
};
// 刪除指定 Cookie
this.removeItem = function (key) {
if (!(key in cookies)) return;
delete cookies[key];
// 從名字數組中移除(若支持 ES5 的 indexOf 会更简洁)
for (var i = 0; i < keys.length; i++) {
if (keys[i] === key) {
keys.splice(i, 1);
break;
}
}
this.length--;
// 把有效期置零即可讓瀏覽器刪除它
document.cookie = key + "=; max-age=0";
};
// 清空全部 Cookie
this.clear = function () {
for (var i = 0; i < keys.length; i++) {
document.cookie = keys[i] + "=; max-age=0";
}
cookies = {};
keys = [];
this.length = 0;
};
}
var store = new CookieStorage(3600, "/");
store.setItem("user", "sheila");
console.log(store.getItem("user")); // sheila
console.log(store.length); // 1
store.removeItem("user");
這樣一層薄封裝之後,團隊裡習慣 Storage API 的人幾乎零成本就能切換到 Cookie 實現。需要注意的是 Cookie 容量有限(通常單域名 4KB 左右),並且每次請求都會帶上,因此不適合存放大數據。