DIV CSS 佈局教程網

純 JavaScript 操作 cookie:記住帳號與密碼的完整實作
編輯:JavaScript綜合知識     

很多登入頁都有「記住密碼」選項,其原理無非就是 cookie 的讀與寫。本文示範不依賴任何函式庫,用原生 JavaScript 完成這件事。

測試方式:輸入帳號密碼並提交,刷新頁面後再輸入同樣的帳號,密碼就會自動帶出。

完整程式碼

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js COOKIE 記住帳號或密碼</title>
<script type="text/javascript">
window.onload = function onLoginLoaded() {
    if (isPostBack == "False") {
        GetLastUser();
    }
}

// 載入時帶出上次的帳號
function GetLastUser() {
    var id = "49BAC005-7D5B-4231-8CEA-16939BEACD67"; // 作為 cookie 名稱的 GUID
    var usr = GetCookie(id);
    if (usr != null) {
        document.getElementById('txtUserName').value = usr;
    } else {
        document.getElementById('txtUserName').value = "001";
    }
    GetPwdAndChk();
}

// 點擊登入時觸發
function SetPwdAndChk() {
    // 取出用戶名
    var usr = document.getElementById('txtUserName').value;
    alert(usr);
    // 把最後一個使用的帳號寫入 cookie
    SetLastUser(usr);

    if (document.getElementById('chkRememberPwd').checked == true) {
        var pwd = document.getElementById('txtPassword').value;
        alert(pwd);
        var expdate = new Date();
        expdate.setTime(expdate.getTime() + 14 * (24 * 60 * 60 * 1000)); // 兩週
        SetCookie(usr, pwd, expdate);
    } else {
        // 沒勾選則立即過期
        ResetCookie();
    }
}

function SetLastUser(usr) {
    var id = "49BAC005-7D5B-4231-8CEA-16939BEACD67";
    var expdate = new Date();
    expdate.setTime(expdate.getTime() + 14 * (24 * 60 * 60 * 1000));
    SetCookie(id, usr, expdate);
}

// 用戶名失去焦點時呼叫
function GetPwdAndChk() {
    var usr = document.getElementById('txtUserName').value;
    var pwd = GetCookie(usr);
    if (pwd != null) {
        document.getElementById('chkRememberPwd').checked = true;
        document.getElementById('txtPassword').value = pwd;
    } else {
        document.getElementById('chkRememberPwd').checked = false;
        document.getElementById('txtPassword').value = "";
    }
}

// 取值
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;
}

var isPostBack = "<%= IsPostBack %>";

function getCookieVal(offset) {
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr == -1) endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}

// 寫入
function SetCookie(name, value, expires) {
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.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 ResetCookie() {
    var usr = document.getElementById('txtUserName').value;
    var expdate = new Date();
    SetCookie(usr, null, expdate);
}
</script>
</head>
<body>
<form id="form1">
<div>
用戶名: <input type="text" ID="txtUserName" onblur="GetPwdAndChk()">
<input type="password" ID="txtPassword"> 密碼:
<input type="checkbox" ID="chkRememberPwd" /> 記住密碼
<input type="button" OnClick="SetPwdAndChk()" value="進入"/>
</div>
</form>
</body>
</html>

設計巧思:用帳號當 cookie 名稱

這段程式碼最特別的地方,是把使用者名稱本身當成 cookie 的 key,值則是密碼。搭配一個固定 GUID 的 cookie 記錄「最後一次使用的帳號」,就能重現「輸入帳號 → 自動帶出密碼」的效果,不必在單一 cookie 裡塞整包 JSON。

另一個細節是綁在帳號欄位的 onblur 而非頁面載入。這樣使用者一離開帳號欄位就立刻帶出對應密碼,換帳號時也能即時清空不屬於他的密碼,體驗上比只在 onload 處理更順。

這份程式碼的幾個問題

1. again,明文儲存密碼

與前一篇相同,把密碼明文寫進 cookie 是不可接受的。cookie 完全在駭客與使用者本人的掌控之下,一旦網站有任何 XSS 漏洞,所有記住的密碼都會被集體撈走。請只記住帳號,登入狀態改用伺服器核發的 HttpOnly token。

2. escape / unescape 已棄用

escape() 與 unescape() 是 deprecated 的函式,且對非 ASCII 字元的編碼方式有缺陷(中文會被編成 %uXXXX,這不是 URL 編碼格式)。應改用 encodeURIComponent() 與 decodeURIComponent()。

3. 以帳號作為 cookie 名稱有風險

使用者名稱可能包含分號、等號、空白等會破壞 cookie 格式的字元,也可能與其他 cookie 名稱碰撞。實務上應使用固定 key(如 lastUsername)並把帳號放進值裡。

4. document.cookie 的手工字串處理容易出錯

自己切字串解析 cookie 的邊界情況很多(名稱是前綴、值為空、多個相同名稱等)。用原生 API 或 js-cookie 都更可靠:

// 寫入
document.cookie = 'lastUsername=' + encodeURIComponent(name)
    + '; expires=' + new Date(Date.now() + 14 * 864e5).toUTCString()
    + '; path=/; SameSite=Lax';

// 讀取
function getCookie(key) {
    const hit = document.cookie.split('; ')
        .find(row => row.startsWith(key + '='));
    return hit ? decodeURIComponent(hit.split('=').slice(1).join('=')) : null;
}

// 刪除:把過期時間設為過去
document.cookie = 'lastUsername=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';

還有一個後端遺留問題

var isPostBack = "<%= IsPostBack %>"; 是 ASP.NET Web Forms 的伺服器端語法。如果這個頁面不是在 ASP.NET 環境中執行,這行會原封不動地輸出成一個語法錯誤的 JavaScript 字串,導致整段 script 掛掉。移植時記得移除。

最後提醒:即使改成記住 token,「記住我」也應該只用在個人裝置上。在公用電腦上勾選這個選項,等於把帳號交給下一個使用者。成熟的網站會偵測、提示,或干脆在共用環境中不提供這個功能。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved