純前端的 Cookie 操作沒有內建的便捷 API,必須自己組字串。本文整理設定與讀取各兩種寫法,並說明實務上必須注意的編碼與安全問題。
方法一:完整指定選項
function setCookie(name, value) {
var exp = new Date();
exp.setTime(exp.getTime() + 1 * 60 * 60 * 1000); // 有效期限 1 小時
document.cookie = name + "=" + encodeURIComponent(value) +
";expires=" + exp.toUTCString() + ";path=/";
}
方法二:最簡寫法
document.cookie = "homepage = https://www.jb51.net";
不指定 expires 時,這是一個工作階段 Cookie,瀏覽器關閉後即消失。字串中可用分號串接多個屬性:expires、path、domain、Secure、HttpOnly、SameSite。
方法一:用正則比對
function getCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) return decodeURIComponent(arr[2]);
return null;
}
方法二:字串切割
function getCookie(key) {
if (key == null) return null;
var arrStr = document.cookie.split(";");
for (var i = 0; i < arrStr.length; i++) {
var temp = arrStr[i].split("=");
if (temp[0].trim() === key) return decodeURIComponent(temp[1]);
}
return null;
}
方法二看似樸素,但實際上更值得推薦:它沒有正則注入的風險(若 key 含有 .、* 等字元,直接拼進 RegExp 會出錯),也更容易除錯。注意 split(";") 後每項開頭通常帶一個空白,務必 trim 再比對。
Cookie 的值不能包含分號、逗號、空白等分隔字元。若使用者輸入的內容直接寫進去,會破壞整個 Cookie 字串結構,甚至被構造出偽造的屬性。因此寫入時用 encodeURIComponent()、讀取時用 decodeURIComponent() 是一對必須成套出現的操作。(注意 escape()/unescape() 已被標準廢棄,不建議再用。)
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
}
刪除的原理是「設定一個已過期的時間」。關鍵是 path 必須與寫入時一致,否則刪不掉——這是最常見的失敗原因。
HttpOnly + Secure + SameSite 設定,讓 JavaScript 根本讀不到。localStorage 比 Cookie 更好用(容量大、不會自動送往伺服器)。