「記住密碼」是很常見的小功能,原理並不複雜:把使用者名稱與密碼寫進 Cookie,頁面載入時再讀出來回填。
<body onload="onLoginLoaded()">
<form id="form1">
用戶名:<input type="text" id="txtUserName" onblur="GetPwdAndChk()">
密碼: <input type="password" id="txtPassword">
<input type="checkbox" id="chkRememberPwd">記住密碼
<input type="button" onclick="SetPwdAndChk()" value="進入">
</form>
</body>
// 寫入
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
}
// 讀取
function getCookie(name) {
var parts = document.cookie.split("; ");
for (var i = 0; i < parts.length; i++) {
var pair = parts[i].split("=");
if (pair[0] == name) return decodeURIComponent(pair[1]);
}
return "";
}
先輸入帳號 jb51、密碼 www.jb51.net,勾選「記住密碼」後關閉頁面。重新開啟時輸入 jb51,密碼欄就會自動帶出先前存的值。
把密碼明文存進 Cookie 是不可接受的做法。Cookie 存在使用者本機,任何能存取該瀏覽器的人都能直接讀出內容,中間 also 容易在 XSS 情境下被腳本偷走。
正確的設計是:
Secure(僅走 HTTPS)、HttpOnly(禁止 JavaScript 讀取)、SameSite(限制跨站傳送)。換言之,上面這段程式碼適合作為理解 Cookie 讀寫機制的練習,但實際產品中不該用它來保存密碼。