「歡迎回來,你今天第 3 次來到本站,上次是星期二下午 3 點」——這種帶點親切感的小功能,用 Cookie 就能完成。原理很簡單:第一次來訪時詢問名字並寫入 Cookie,同時記錄時間戳與計數器;之後每次載入頁面,就把這三個值讀出來更新。
以下是一個可直接運作的完整範例,包含 GetCookie、SetCookie、DeleteCookie 三個基礎工具函數,以及 Who、When、Count 三個業務函數。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用 Cookie 記錄訪客資訊</title>
<script language="JavaScript">
var expDays = 30;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays * 24 * 60 * 60 * 1000));
// 取得訪客姓名,沒有則詢問並寫入
function Who() {
var VisitorName = GetCookie('VisitorName');
if (VisitorName == null) {
VisitorName = prompt("您的尊姓大名:");
SetCookie('VisitorName', VisitorName, exp);
}
return VisitorName;
}
// 讀取上次來訪時間,並更新為現在
function When() {
var rightNow = new Date();
var WWHTime = GetCookie('WWhenH') * 1;
var lastHere = new Date(WWHTime);
var text = "" + lastHere;
var WWHText = text.substring(0, 3) + ", " + text.substring(4, 11) +
" at " + text.substring(11, 16);
SetCookie('WWhenH', rightNow.getTime(), exp);
return WWHText;
}
// 累計來訪次數
function Count() {
var WWHCount = GetCookie('WWHCount');
if (WWHCount == null) {
WWHCount = 0;
} else {
WWHCount++;
}
SetCookie('WWHCount', WWHCount, exp);
return WWHCount;
}
// 重新設定身分並重置統計
function set() {
var VisitorName = prompt("Who are you?");
SetCookie('VisitorName', VisitorName, exp);
SetCookie('WWHCount', 0, exp);
SetCookie('WWhenH', 0, exp);
}
// ===== 基礎工具函數 =====
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) { endstr = document.cookie.length; }
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) { break; }
}
return null;
}
function SetCookie(name, value) {
var argv = SetCookie.arguments;
var argc = argv.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function DeleteCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = GetCookie(name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
</script>
</head>
<body>
提示:第一次來到本頁時會請你輸入姓名,之後每當你回來,它會告訴你這是第幾次來訪,並註明上次的時間。
<br/>
<script language="JavaScript">
if (Count() == 0) {
document.write("您好!" + Who() + "。您首次來這兒,請多提寶貴意見。");
} else {
document.write("您好!" + Who() + "。您已來這兒 " + Count() +
" 次了,最後一次在 " + When() + "。");
}
</script>
</body>
</html>
幾個實作細節值得留意:escape() 與 unescape() 已屬老舊 API,新專案建議改用 encodeURIComponent() 與 decodeURIComponent(),對中文的處理更可靠。另外 Cookie 是明文儲存在使用者端的,不適合存放任何敏感資料,身分驗證應交由伺服器端的 Session 或簽章過的 token 處理。若只是想在瀏覽器端記住偏好設定,現代的 localStorage 容量更大、API 也更清爽,可以優先考慮。