Cookie 是前端保存少量狀態的傳統手段。本文從基本操作談到路徑與網域的作用範圍,最後整理成三個可直接重用的通用函式。
每個 cookie 都是一個「名稱/值」配對,直接賦值給 document.cookie 即可:
document.cookie = "userId=828";
要存多筆時用分號加空格隔開:
document.cookie = "userId=828; userName=hulk";
名稱與值中不可使用分號、逗號、等號與空格。解法是用 escape() 編碼,中文亂碼問題也能一併解決:
document.cookie = "str=" + escape("I love ajax");
// 實際存成 str=I%20love%20ajax
// 讀出後需以 unescape() 解碼還原
值得注意的是,document.cookie 看起來像一般屬性,行為卻完全不同——重複賦值並不會覆蓋先前的內容,而是相當於不斷呼叫 addCookie:
document.cookie = "userId=828"; document.cookie = "userName=hulk"; // 兩筆並存,而非取代
若要修改某個 cookie 的值,重新賦同名即可:
document.cookie = "userId=929";
麻煩之處在於只能一次取得全部,必須自己解析:
var strcookie = document.cookie; // "userId=828; userName=hulk"
var arrcookie = strcookie.split("; ");
var userId;
for (var i = 0; i < arrcookie.length; i++) {
var arr = arrcookie[i].split("=");
if ("userId" == arr[0]) {
userId = arr[1];
break;
}
}
alert(userId);
不指定期限的是「工作階段 cookie」,只存在記憶體中,瀏覽器關閉就消失。要長期保存就得給 expires:
var date = new Date(); var expireDays = 10; date.setTime(date.getTime() + expireDays * 24 * 3600 * 1000); document.cookie = "userId=828; userName=hulk; expire=" + date.toGMTString();
把期限設為過去時間即可:
var date = new Date(); date.setTime(date.getTime() - 10000); document.cookie = "userId=828; expire=" + date.toGMTString();
預設情況下,同一目錄及其子目錄的頁面都能讀到該 cookie。用 path 參數可以收窄或放寬範圍:
document.cookie = "userId=320; path=/shop"; // 僅 shop 目錄可用 document.cookie = "userId=320; path=/"; // 全站可用
預設同一網域下的不同子網域無法共用 cookie,可用 domain 打開:
document.cookie = "name=value; domain=.google.com";
把上述邏輯收攏成函式,就能到處重用。
function setCookie(name, value, expireHours) {
var cookieString = name + "=" + escape(value);
if (expireHours > 0) {
var date = new Date();
date.setTime(date.getTime() + expireHours * 3600 * 1000);
cookieString += "; expire=" + date.toGMTString();
}
document.cookie = cookieString;
}
function getCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) return unescape(arr[2]);
return null;
}
function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
Cookie 會隨每次請求送到伺服器,因此不適合存放大量資料;容量上限一般為單筆 4KB 左右。敏感資訊(例如權杖、密碼)請加上 Secure 與 HttpOnly 旗標,避免被腳本讀取或在傳輸中曝光。若只是單頁應用內部要暫存狀態,localStorage 與 sessionStorage 會是更方便的選擇。