原生 document.cookie 只是一串以分號分隔的文字,讀寫都得自己切字串,寫多了很容易出錯。把它封裝成一個類,是每個前端專案早期都值得做的事。
一、設定 Cookie
var cookie = new JSCookie();
// 基本設定
cookie.SetCookie("key1", "val1");
// 指定過期時間為一年後
var expire_time = new Date();
expire_time.setFullYear(expire_time.getFullYear() + 1);
cookie.SetCookie("key2", "val2", expire_time);
// 指定 domain 與 path
cookie.SetCookie("key3", "val3", expire_time, ".example.com", "/");
// 以 & 分隔寫入多個子鍵
cookie.SetCookie("key4", "k1=1&k2=2&k3=3");二、讀取 Cookie
cookie.GetCookie("key1");
cookie.GetCookie("key2");
cookie.GetCookie("key3");
cookie.GetCookie("key4");
cookie.GetChild("key4", "k1"); // 取出 key4 中的子鍵 k1三、刪除 Cookie
cookie.Expire("key1");
cookie.Expire("key2");
cookie.Expire("key3");
cookie.Expire("key4"); <script type="text/javascript">
String.prototype.Trim = function() {
return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
};
function JSCookie() {
// 讀取單一 cookie 值
this.GetCookie = function(key) {
var cookieArray = document.cookie.split(';');
var getvalue = "";
for (var i = 0; i < cookieArray.length; i++) {
if (cookieArray[i].Trim().substr(0, key.length) == key) {
getvalue = cookieArray[i].Trim().substr(key.length + 1);
break;
}
}
return getvalue;
};
// 讀取子鍵
this.GetChild = function(cookiekey, childkey) {
var childs = this.GetCookie(cookiekey).split('&');
var getvalue = "";
for (var i = 0; i < childs.length; i++) {
if (childs[i].Trim().substr(0, childkey.length) == childkey) {
getvalue = childs[i].Trim().substr(childkey.length + 1);
break;
}
}
return getvalue;
};
// 寫入
this.SetCookie = function(key, value, expire, domain, path) {
var cookie = "";
if (key != null && value != null) cookie += key + "=" + value + ";";
if (expire != null) cookie += "expires=" + expire.toGMTString() + ";";
if (domain != null) cookie += "domain=" + domain + ";";
if (path != null) cookie += "path=" + path + ";";
document.cookie = cookie;
};
// 刪除:把過期時間設為過去
this.Expire = function(key) {
var expire_time = new Date();
expire_time.setFullYear(expire_time.getFullYear() - 1);
document.cookie = " " + key + "=e;expires=" + expire_time + ";";
};
}
</script>刪除的原理。瀏覽器沒有刪除 cookie 的 API,唯一方法是把它設成已過期。這裡把年份減一,是最常見的做法。
key 比對要用 = 而非 substr。原實作用 substr(0, key.length) == key 做前綴比對,這會有誤判風險——查 "user" 時可能命中 "username"。正確做法是先以 '=' 切出鍵名再比對:
this.GetCookie = function(key) {
var pairs = document.cookie ? document.cookie.split(';') : [];
for (var i = 0; i < pairs.length; i++) {
var idx = pairs[i].indexOf('=');
var name = pairs[i].slice(0, idx).trim();
if (name === key) return pairs[i].slice(idx + 1);
}
return "";
};值必須編碼。Cookie 值不能含分號、逗號與空白。寫入時應 encodeURIComponent(value),讀取時 decodeURIComponent(),否則中文或特殊字元會直接壞掉。
toGMTString 已棄用。請改用 toUTCString(),兩者輸出格式相同但前者已被標準標記為 obsolete。
String.prototype 擴充要謹慎。為原型掛上可列舉屬性會污染所有 for-in 迴圈。ES5 之後請用 Object.defineProperty 設為不可列舉,或直接改用 str.trim()(現已全面支援)。
最後提醒:Cookie 容量約 4KB 且每次請求都會隨附送出,大量資料應改用 localStorage 或 sessionStorage。另外,Cookie 不應存放敏感資訊,正式環境請加上 Secure 與 SameSite 屬性。