直接操作 document.cookie 字串很麻煩,每次都要自己切分、比對、編碼。把它包成一個函式,之後只要一行就能存取。
// 存值:以 "day" 為 key,把 "7天" 存進 cookie,有效期限 7 天
var value = "7天";
tools.cookie("day", value, { expires: 7 });
// 取值:以 "day" 為 key 取出對應的值
var v = tools.cookie("day");
tools.cookie = function (name, value, options) {
if (typeof value != 'undefined') {
// 有傳入 value → 設定 cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1; // 負的過期時間 → 立即失效
}
var expires = '';
if (options.expires &&
(typeof options.expires == 'number' || options.expires.toGMTString)) {
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 屬性,max-age 在舊 IE 上不支援
expires = '; expires=' + date.toGMTString();
}
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 {
// 只傳入 name → 讀取 cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// 判斷這筆是否以我們要的名稱開頭
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
null 時,會轉成空字串並附上 expires = -1,達到刪除效果。encodeURIComponent、讀取用 decodeURIComponent,避免中文或特殊字元出問題。
// 寫入
document.cookie = "day=" + encodeURIComponent("7天") +
"; max-age=" + (7 * 24 * 3600) + "; path=/; SameSite=Lax";
// 讀取(ES6 版本)
const getCookie = (name) =>
document.cookie.split("; ")
.find(row => row.startsWith(name + "="))
?.split("=")[1];
目前主流做法是加上 SameSite 屬性以降低跨站請求風險;敏感資訊(例如登入權杖)則應設定 HttpOnly,讓 JavaScript 完全無法讀取。