萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 實現「記住賬號密碼」功能(無依賴 Cookie 操作封裝)

不依賴 jQuery,純原生 JS 封裝 Cookie 讀寫工具函數,實現登錄頁「記住賬號、記住密碼、自動勾選」完整流程。本文提供完整可運行的單文件演示,適合無框架環境、老項目維護、教學演示 Cookie 底層操作。

核心 Cookie 工具函數

// 寫入 Cookie
function SetCookie(name, value, expires, path, domain, secure) {
    var str = name + "=" + escape(value);
    if (expires) str += "; expires=" + expires.toGMTString();
    if (path)    str += "; path=" + path;
    if (domain)  str += "; domain=" + domain;
    if (secure)  str += "; secure";
    document.cookie = str;
}

// 讀取 Cookie
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 getCookieVal(offset) {
    var end = document.cookie.indexOf(";", offset);
    if (end === -1) end = document.cookie.length;
    return unescape(document.cookie.substring(offset, end));
}

// 刪除 Cookie(設置過期時間為過去)
function ResetCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    SetCookie(name, "", exp);
}

業務邏輯封裝

var COOKIE_NS = "49BAC005-7D5B-4231-8CEA-16939BEACD67"; // 命名空間避免衝突
var EXPIRE_DAYS = 14;

function getExpDate() {
    var d = new Date();
    d.setTime(d.getTime() + EXPIRE_DAYS * 24 * 60 * 60 * 1000);
    return d;
}

// 頁面加載:嘗試填充用戶名
window.onload = function() {
    if (isPostBack === "False") { // ASP.NET 環境判斷,純前端可移除
        GetLastUser();
    }
};

function GetLastUser() {
    var user = GetCookie(COOKIE_NS);
    document.getElementById("txtUserName").value = user || "001";
    GetPwdAndChk();
}

// 用戶名失焦:嘗試填充密碼並勾選
function GetPwdAndChk() {
    var user = document.getElementById("txtUserName").value;
    var pwd = GetCookie(user);
    if (pwd) {
        document.getElementById("chkRememberPwd").checked = true;
        document.getElementById("txtPassword").value = pwd;
    } else {
        document.getElementById("chkRememberPwd").checked = false;
        document.getElementById("txtPassword").value = "";
    }
}

// 登錄按鈕:根據勾選狀態寫入/清除 Cookie
function SetPwdAndChk() {
    var user = document.getElementById("txtUserName").value;
    SetLastUser(user); // 記住最後用戶名

    if (document.getElementById("chkRememberPwd").checked) {
        var pwd = document.getElementById("txtPassword").value;
        SetCookie(user, pwd, getExpDate());
    } else {
        ResetCookie(user);
    }
    // 此處接真實登錄驗證邏輯
}

function SetLastUser(user) {
    SetCookie(COOKIE_NS, user, getExpDate());
}

HTML 表單

<form id="form1">
<div>
    用戶名: <input type="text" id="txtUserName" onblur="GetPwdAndChk()" />
    密碼: <input type="password" id="txtPassword" />
    <input type="checkbox" id="chkRememberPwd" /> 記住密碼
    <input type="button" value="進入" onclick="SetPwdAndChk()" />
</div>
</form>

關鍵設計點

  1. 雙層 Cookie 結構:
     - 固定 Key COOKIE_NS 存「最後登錄用戶名」。
     - 動態 Key = 用戶名,存對應密碼。
     實現「切換用戶名自動填充對應密碼」。
  2. 編碼處理:escape/unescape 處理特殊字符(現代建議 encodeURIComponent/decodeURIComponent)。
  3. 過期時間統一:封裝 getExpDate() 避免硬編碼重複。
  4. ASP.NET 兼容:保留 isPostBack 判斷,純前端項目可刪除。

安全警示(同 jQuery 版)

明文密碼存 Cookie 極度危險! 僅供教學/內網演示。生產環境必須:

  • 後端下發 HttpOnly Secure SameSite=Strict 的 Refresh Token Cookie。
  • 前端**不存**密碼,僅存用戶名(可加密)或憑證 Token。
  • 全站 HTTPS,防止 Cookie 劫持。

現代化重構建議

// 使用現代 API 簡化 Cookie 操作
const Cookie = {
    set(name, value, days=14) {
        const d = new Date(Date.now() + days*864e5).toUTCString();
        document.cookie = `${name}=${encodeURIComponent(value)}; expires=${d}; path=/; SameSite=Strict`;
    },
    get(name) {
        const m = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
        return m ? decodeURIComponent(m[2]) : null;
    },
    remove(name) { this.set(name, "", -1); }
};

// 業務邏輯同前,調用 Cookie.set/get/remove

原生 JS 版本讓你徹底理解 Cookie 協議細節(域、路徑、過期、編碼、安全屬性),是進階前端工程師的必修內功。

copyright © 萬盛學電腦網 all rights reserved