「歡迎回來,某某」這種小細節,用 cookie 就能做到。流程是:第一次造訪時跳出 prompt 詢問暱稱並寫入 cookie(設定一年有效),之後每次載入先讀 cookie,有值就問候,沒有才詢問。
<!DOCTYPE html>
<html>
<head>
<script>
// 讀取指定名稱的 cookie
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;
}
// 寫入 cookie,exdays 為有效天數
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>
escape/unescape 已不建議使用。它們對非 ASCII 字元的處理不正確,中文暱稱容易變亂碼。請改用 encodeURIComponent() 與 decodeURIComponent()。
字串比對 cookie 值要小心前綴問題。用 indexOf 找 "name=" 時,若同時存在 username 與 user 兩個 cookie,可能誤中。較穩妥的做法是先 document.cookie.split('; ') 再逐筆比對第一個等號前的鍵名。
加上 SameSite 與 path。寫入時一併指定 ; path=/; SameSite=Lax,可避免 cookie 在不同路徑下讀不到,也能降低跨站請求被附帶的風險。
別把敏感資料放 cookie。身分權杖請使用 HttpOnly 的 cookie(由後端設定,前端讀不到),前端可讀的 cookie 只放顯示用的偏好設定即可。
最後記得,cookie 是「使用者可修改」的資料,任何以 cookie 內容作為權限判斷依據的設計都等於沒有防護。