這是一個很經典的 cookie 入門練習:使用者第一次來訪時詢問暱稱並寫入 cookie;下次再來時讀出來,直接問候。它涵蓋了 cookie 讀、寫、設過期三個基本動作。
<!DOCTYPE html>
<html>
<head>
<script>
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
} else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function checkCookie() {
var username = getCookie("username");
if (username != null && username != "") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != null && username != "") {
setCookie("username", username, 365);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
為什麼 document.cookie 那麼難讀?因為它不是物件,而是一個單一字串,所有 cookie 都被分號串在一起,像 "a=1; username=John; theme=dark"。所以 getCookie 必須自己切字串——先找 " name=",找不到再找開頭的 "name="(處理第一個 cookie 沒有前導空格的情況),最後切到分號或字串結尾。
為什麼要 escape/unescape?因為 cookie 的值不能含分號、逗號、空白等字元,必須先編碼。這兩個函式已被標記為不建議使用,現代請改用 encodeURIComponent() 與 decodeURIComponent()。
不設 expires 會怎樣?會變成 session cookie,瀏覽器關掉就没了。範例設 365 天是為了讓它長期保留。
今天處理 cookie 有兩個更好的選擇。一是用 document.cookie 的簡化寫法搭配 SameSite;二是直接用 localStorage(純前端資料)或 sessionStorage:
localStorage.setItem("username", "John");
localStorage.getItem("username");
差別在於:cookie 會隨每次請求自動送往伺服器,適合 session、身分驗證;localStorage 純存在瀏覽器,容量更大,適合非敏感的前端狀態。使用者暱稱這種資料放 localStorage 更合適,也不必有 escape 的困擾。