在 localStorage 普及之前,Cookie 是瀏覽器端保存狀態的唯一手段。即使今天有了更多選擇,Cookie 因為會隨請求自動送往伺服器,在身份識別等場景中依然無可取代。
Cookie 是一小段以檔案形式保存在客戶端硬碟的用戶資料,由所造訪的網站建立,用來長期保存客戶端與網站之間的會話資訊,並且只允許建立它的網站讀取。
檔案命名方式:
Cookie.txt使用者名稱@網域名稱.txt寫入:
document.cookie = "key=value; expires=有效日期; path=/";
讀取:
document.cookie
刪除(把過期時間設為過去):
document.cookie = "key=; expires=過去日期";
這裡有個關鍵認知:document.cookie 讀取時回傳的是該域名下所有 Cookie 組成的單一字串,並不是一個物件。所以你必須自己解析:
function getCookie(name) {
var match = document.cookie.match(
new RegExp('(?:^|; )' + name + '=([^;]*)')
);
return match ? decodeURIComponent(match[1]) : null;
}
有效日期格式為 Wdy, DD-Mon-YY HH:MM:SS GMT(Wdy 為英文星期、Mon 為英文月份)。除此之外還有三個重要屬性:
path:Cookie 生效的路徑範圍。domain:Cookie 生效的網域範圍。secure:僅在 HTTPS 連線下傳送。容量限制方面:每個網域最多可建立 20 個 Cookie,每個瀏覽器最多存 300 個、每個約 4KB。此外,使用者有權禁用 Cookie 寫入——這意味著任何依賴 Cookie 的功能都必須有降級方案。
<!DOCTYPE html>
<html>
<head>
<title>cookieTest.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
var today = new Date();
var expiredDay = new Date();
var msPerMonth = 1000 * 60 * 60 * 24 * 30;
expiredDay.setTime(today.getTime() + msPerMonth); // 一個月之後過期
// 寫入 cookie
document.cookie = "name=mengdd; expires=" + expiredDay.toUTCString();
document.writeln("cookie 已經寫到硬盤上了");
document.writeln("內容是:" + document.cookie);
document.writeln("expire day: " + expiredDay.toUTCString());
</script>
</body>
</html>
這裡要注意兩點:日期字串應使用 toUTCString()(toGMTString() 是它的別名,已被標記為不建議使用);而 Cookie 的值若含空白、分號或中文等非 ASCII 字元,必須先 encodeURIComponent() 編碼,否則會被截斷。
HttpOnly:加上這個旗標後,JavaScript 將無法讀取該 Cookie,能大幅降低 XSS 攻擊偷竊會話的風險。遺憾的是這個屬性只能由伺服器端設定,前端無能為力。
Secure:確保 Cookie 只在加密連線中傳輸,避免在 HTTP 明文通道被竊聽。
SameSite:限制跨站請求是否附帶 Cookie,是防禦 CSRF 的關鍵設定。
因此實務上的分工是:敏感憑證(如 session id)一律設為 HttpOnly; Secure; SameSite=Strict,由後端管理;前端只負責存放非敏感的使用者偏好設定。
判斷依據:資料需要讓伺服器看到 → Cookie;只在瀏覽器端使用 → localStorage;敏感憑證 → 只能交給後端以 HttpOnly Cookie 管理。