原生操作 Cookie 是一件相當繁瑣的事。Cookie 以字串形式儲存資訊,讀取時要自己切分、比對名稱、解碼,寫入時又得手工組出 expires、path、domain 等屬性,型別轉換也得自己處理。在會頻繁使用 Cookie 的專案裡,這些重複勞動足以成為負擔。封裝一個統一介面,是相當值得的投資。
設計目標是讓一個函式同時肩負三種任務:傳入值時寫入、傳入 null 時刪除、不傳值時讀取。另外還能透過 options 指定有效期、路徑、作用域與安全性。
var Cookie = function (name, value, options) {
// 有傳入第二個參數,代表要寫入或刪除
if (typeof value != 'undefined') {
options = options || {};
// 傳入 null 時,把失效時間設為過去,等同刪除
if (value === null) {
options.expires = -1;
}
var expires = '';
// expires 可以是天數,也可以是 Date 物件
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString();
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
// 組合成字串後寫入
document.cookie = [name, '=', encodeURIComponent(value),
expires, path, domain, secure].join('');
} else {
// 未傳值,代表要讀取
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = (cookies[i] || "").replace(/^\s+|\s+$/g, "");
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
幾個實作重點:encodeURIComponent/decodeURIComponent 一對必須成組使用,否則值裡有分號或等號時會破壞格式;判斷名稱時加上 name + '=' 而非只比 name,可以避免 user 誤中 username;用陣列 join('') 組字串比連續串接更清晰。
寫入:
// 最簡單的寫入
Cookie("user", "baidu");
// 寫入並指定多項設定
Cookie("user", "baidu", {
expires: 10, // 有效期 10 天
path: "/", // 全站有效
domain: "www.baidu.com", // 有效網域
secure: true // 僅透過加密傳輸
});
讀取:
Cookie("user");
刪除:
Cookie("user", null);
如果偏好「一個函式做一件事」的風格,可以拆成 write/read/erase:
// 寫入 cookie
function writeCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
// 讀取 cookie
function readCookie(name) {
var searchName = name + "=";
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var c = cookies[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(searchName) == 0) {
return c.substring(searchName.length, c.length);
}
}
return null;
}
// 刪除 cookie:把時間設為過去即可
function eraseCookie(name) {
writeCookie(name, "", -1);
}
這個版本更短更好讀,缺點是沒有做編碼與解碼,值裡若含特殊字元會出問題;另外 eraseCookie 透過 writeCookie 傳入 -1 天,時間點落在過去,效果等同刪除。
兩種風格各有適用場景:單一函式的寫法在物件導向或需要大量傳遞選項時較靈活;拆分式的寫法在一般業務中更直觀。真正實作時建議再補上三件事——對 name 與 value 都進行編碼、讀取時比對完整 name= 前綴避免誤中、以及明確處理「找不到」與「值為空字串」兩種不同情況。
最後要提醒的是,Cookie 不適合存放敏感資料,容量也有上限(通常單域名稱 4KB 左右);需要保存較多或較敏感狀態時,localStorage、sessionStorage 或後端 session 會是更合適的選擇。