紀錄工作經驗、相關知識,解決技術相關問題。

HTML, 新手 Jamp Holes, 網站相關

HTML input 自動填入(Autofill)常見問題解析:樣式覆蓋、關閉策略與狀態同步

HTML input 自動填入(Autofill)常見問題解析:樣式覆蓋、關閉策略與狀態同步 特色圖片

想了解 autocomplete 的 Token 語法與屬性值,可前往 HTML input autocomplete 屬性規範與瀏覽器自動填入(Autofill)實作要點。本文直接切入 HTML input 自動填入(Autofill) 的三個工程問題:深色主題的輸入框被自動填入後變成亮藍或淡黃底色、後台設了 autocomplete="off" 仍被填入管理員自己的帳密,以及自動填入後浮動標籤重疊、前端框架抓不到值。 游標消失、預覽字型、Honeypot 誤填、200 欄位上限等邊界問題,整理在 HTML input 自動填入進階排查:游標消失、預覽字型、Honeypot 誤填與 200 欄位上限。

想直接複製範本,可跳到 CSS 樣式覆蓋範本、後台表單防誤填範本 或 React 偵測自動填入範本。


一、從標準自動填入到工程衝突:為什麼 Autofill 會影響樣式、後台表單與前端狀態?

先看「標準寫法」在哪些情境下會與瀏覽器的自動填入機制衝突。

1. 原本正常的標準寫法與瓶頸:當瀏覽器預設行為與產品需求衝突時

假設我們開發一套深色主題(Dark Mode)的企業後台,按標準 HTML 與 CSS 撰寫「新增員工帳號」表單:

<!-- 原本正常的標準寫法:深色主題輸入框 + 嘗試以 autocomplete="off" 關閉自動填入 -->
<form action="/admin/users/create" method="POST" autocomplete="off">
  <div class="floating-field">
    <input
      type="text"
      id="emp-account"
      name="account"
      placeholder=" "
      autocomplete="off"
      required
    >
    <label for="emp-account">新進員工帳號</label>
  </div>

  <div class="floating-field">
    <input
      type="password"
      id="emp-password"
      name="password"
      placeholder=" "
      autocomplete="off"
      required
    >
    <label for="emp-password">設定初始密碼</label>
  </div>
</form>

<style>
  .floating-field input {
    background-color: #0f172a !important; /* 企圖強制維持深色背景 */
    color: #f8fafc !important;
  }
  /* 當輸入框聚焦或非空時,將浮動標籤往上推 */
  .floating-field input:focus + label,
  .floating-field input:not(:placeholder-shown) + label {
    transform: translateY(-1.25rem) scale(0.85);
  }
</style>

這段看似合規的程式碼,在 Chrome、Edge 或 Safari 觸發自動填入時,會同時發生三個問題:

  1. !important 背景色失效:即使加了 background-color: #0f172a !important;,自動填入後背景仍被刷成淺藍色(Chrome/Edge 為 rgb(232, 240, 254))或淡黃色(Safari 為 #FAFFBD)。
  2. autocomplete="off" 被忽略:管理員打開「新增員工」頁面時,瀏覽器把文字框加密碼框當成登入表單,把管理員自己的登入帳密填進新員工的欄位。
  3. 載入時預填的帳密,JavaScript 讀不到:Chrome 在載入時預填已儲存的帳密,使用者與頁面互動之前 input.value 仍是空字串,也不會收到 input 事件,靠它們判斷狀態的浮動標籤與前端框架會以為欄位是空的。

2. 瀏覽器底層介入機制:User-Agent !important 樣式表、密碼庫優先策略與預填值隔離

以下整理這三點的瀏覽器實作:

衝突維度瀏覽器底層實作開發者對策
1. 強制背景色與字色Chromium、WebKit、Gecko 的 User-Agent 樣式表對自動填入狀態都寫了 !important 的背景與字色,用固定底色標示自動填入的欄位用 -webkit-box-shadow: ... inset 內陰影覆蓋,以 -webkit-text-fill-color 控制文字色
2. 忽略登入欄位的 off依 MDN,許多現代瀏覽器對帳號密碼欄位不支援 autocomplete="off",理由是密碼管理讓使用者能選用較強的密碼非憑證欄用 off;「新增員工/設定新密碼」欄標記 autocomplete="new-password"
3. 載入時預填值暫不開放給 JavaScriptChrome 載入時預填的帳密先以建議值(suggested value)顯示,互動前 input.value 為 ""(PasswordValueGatekeeper),原始碼註解說明是為了保護隱私並縮小攻擊面浮動標籤補 :autofill 選擇器,並以 @keyframes 的 animationstart 通知前端框架

二、CSS 樣式覆蓋實務:處理 :autofill 與 :-webkit-autofill 的強制背景色與字色

要讓自動填入後的輸入框維持產品原有的視覺設計,必須針對瀏覽器的 User-Agent 樣式表特性進行繞道覆蓋。

1. 為什麼直接設定 background-color: transparent !important 無法蓋掉藍底或黃底?

檢視 Chromium 原始碼中的 User-Agent 樣式表(html.css),可以看到欄位處於自動填入狀態時的規則:

/* Chromium 瀏覽器內建的 User-Agent 強制樣式(開發者無法直接用 background-color 覆寫) */
input:-internal-autofill-previewed,
input:-internal-autofill-selected,
textarea:-internal-autofill-previewed,
textarea:-internal-autofill-selected,
select:-internal-autofill-previewed,
select:-internal-autofill-selected {
  appearance: menulist-button;
  background-image: none !important;
  background-color: light-dark(#E8F0FE, rgba(70, 90, 126, 0.4)) !important;
  color: FieldText !important;
}

根據 W3C CSS Cascading and Inheritance Level 4,User-Agent !important 的優先權高於 Author !important,所以不論選擇器權重多高,background-color、background-image 與 color 都無法覆寫瀏覽器的 !important 規則。同一份規範把「Transition declarations」排在 UA !important 之上,這就是下方範本 transition: background-color 99999s 能讓背景色維持原樣的原因。

2. 深淺色主題通用解法:結合標準 :autofill、內陰影 inset、-webkit-text-fill-color 與 caret-color

既然 background-color 與 color 被鎖死,改用沒被鎖死、卻能蓋過強制底色與字色的三個屬性:

  1. -webkit-box-shadow: 0 0 0 1000px <背景色> inset:極大範圍的向內陰影繪製在背景色之上,完全遮蓋強制底色。
  2. -webkit-text-fill-color: <文字色>:能正常改寫自動填入的文字顏色。
  3. caret-color: <游標色>:明確指定游標顏色,避免深色背景上游標維持黑色而看不見(原因見 進階排查文章)。

標準的 :autofill 偽類已被 Chrome 110+、Edge 110+、Safari 15+、Firefox 86+ 支援(Firefox 只對自動填入的帳號密碼欄位比對成功),規範也把 :-webkit-autofill 當成它的舊名稱(legacy selector alias)。搭配 CSS 變數寫成:

:root {
  --input-autofill-bg: #ffffff;
  --input-autofill-text: #0f172a;
}

@media (prefers-color-scheme: dark) {
  :root {
    --input-autofill-bg: #1e293b;
    --input-autofill-text: #f8fafc;
  }
}

/* 1. 針對 WebKit / Blink 核心(Chrome, Safari, Edge)涵蓋所有互動狀態 */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
  -webkit-box-shadow: 0 0 0 1000px var(--input-autofill-bg) inset !important;
  -webkit-text-fill-color: var(--input-autofill-text) !important;
  caret-color: var(--input-autofill-text) !important;
  background-clip: content-box !important;
  /* 若需要完全透明背景(例如毛玻璃材質輸入框),可將背景色過渡時間拉長至 99999 秒 */
  transition: background-color 99999s ease-out 0s;
}

/* 2. 針對標準 CSS Selectors Level 4 (:autofill,含 Firefox 支援) */
input:autofill {
  box-shadow: 0 0 0 1000px var(--input-autofill-bg) inset !important;
  -webkit-text-fill-color: var(--input-autofill-text) !important;
  color: var(--input-autofill-text) !important;
  caret-color: var(--input-autofill-text) !important;
}

3. 解決 Floating Label(浮動標籤)在自動填入時與文字重疊的問題

浮動標籤通常用 <input placeholder=" "> 搭配 input:not(:placeholder-shown) + label 把標籤上移。頁面載入被預填時,要把 :-webkit-autofill 與 :autofill 也納入觸發條件,並分開寫成兩條規則(原因見 進階排查文章):

.floating-field {
  position: relative;
}

/* 正常聚焦或已有輸入文字時,將標籤上移縮小 */
.floating-field input:focus + label,
.floating-field input:not(:placeholder-shown) + label {
  transform: translateY(-1.25rem) scale(0.85);
  color: #2563eb;
}

/* 當瀏覽器處於自動填入狀態時,同步將標籤上移(獨立規則防解析失敗) */
.floating-field input:-webkit-autofill + label {
  transform: translateY(-1.25rem) scale(0.85);
  color: #2563eb;
}

.floating-field input:autofill + label {
  transform: translateY(-1.25rem) scale(0.85);
  color: #2563eb;
}

三、表單自動填入關閉與隔離策略:當 autocomplete="off" 被忽略時的標準做法

第二個常見問題是:不想讓瀏覽器帶入舊資料的欄位,該怎麼正確關閉?要依欄位屬於一般文字或帳號密碼憑證採取不同策略。

1. 一般非憑證欄位(搜尋框、優惠碼、單次查詢欄)的歷史紀錄關閉寫法

站內搜尋框、訂單編號查詢、優惠碼等非帳號密碼的欄位,可以用 autocomplete="off"。依 MDN,它會告訴瀏覽器不要儲存使用者在此欄位輸入的資料供日後自動完成,也不要把表單資料快取在工作階段歷史中;設定後瀏覽器仍給建議時,就更換 name:

<!-- 一般查詢或篩選欄位:使用標準 autocomplete="off" 即可正常關閉下拉歷史紀錄 -->
<div class="form-field">
  <label for="order-search">查詢訂單編號</label>
  <input
    type="search"
    id="order-search"
    name="orderQuery"
    autocomplete="off"
    autocapitalize="none"
    autocorrect="off"
    spellcheck="false"
  >
</div>

2. 後台管理系統「新增員工/編輯他人帳號」避免管理員自身帳密被誤填的寫法

在 ERP、CMS 或企業後台的「新增員工/建立客戶帳號」表單,已登入的管理員打開表單時,密碼管理器看到文字框加 type="password",即使寫了 autocomplete="off",仍會把管理員自己的帳號密碼塞進欄位。

根據 MDN Web Docs — Turning off form autocompletion 的官方指引,此時不應使用 autocomplete="off",而是應該將密碼欄位明確標記為 autocomplete="new-password":

<!-- 後台管理系統「建立新員工帳號」表單:防止帶入管理員自身帳密的標準配置 -->
<form id="admin-create-user-form" action="/api/admin/users" method="POST" autocomplete="off">
  <div class="form-field">
    <label for="staff-email">新員工企業信箱</label>
    <!-- 新員工信箱不是管理員自己的登入帳號,標記為 off -->
    <input
      type="email"
      id="staff-email"
      name="staffEmail"
      autocomplete="off"
      required
    >
  </div>

  <div class="form-field">
    <label for="staff-init-pwd">設定員工初始密碼</label>
    <!-- 關鍵設定:使用 new-password 明確告知密碼管理器「不要帶入管理員的現有密碼(current-password)」 -->
    <input
      type="password"
      id="staff-init-pwd"
      name="staffInitialPassword"
      autocomplete="new-password"
      required
    >
  </div>

  <button type="submit">建立員工帳號</button>
</form>

autocomplete="new-password" 告訴瀏覽器這個欄位要設定新密碼,而不是填入已儲存的密碼。MDN 提醒這只是 hint,部分瀏覽器可能不照做,送出前仍應在後端確認資料。

3. 為什麼網路上流傳的 autocomplete="nope" 或 autocomplete="false" 屬於反模式?

論壇上常見 autocomplete="nope" 或 "false" 的建議,但 WHATWG 規範的合法關閉值只有 "off"。

依規範處理流程,無法識別的 Token 會當成沒寫:欄位依所屬 <form> 的 autocomplete 狀態決定,多半是 on,瀏覽器仍可啟發式判斷並照樣填入。因此非憑證欄位用 off,新密碼欄位用 new-password。


四、前端狀態同步(React / Vue / Vanilla JS):偵測自動填入並同步資料流

當使用者主動從下拉選單點選自動填入項目時,Chrome 會正常派發 input 與 change 事件。但頁面載入、Chrome 自動預填已儲存的登入帳密時,PasswordValueGatekeeper 先把值當成建議值顯示,使用者與頁面互動(點擊、按鍵)之前,input.value 仍是 "",也不會觸發 onChange。事件的基礎行為見 HTML input 事件全解析。

1. 為什麼頁面初次載入的預填狀態不會立即觸發 React onChange?

常見寫法是 <button type="submit" disabled={!username || !password}>。使用者回到登入頁,Chrome 已預填好帳密,但使用者還沒互動,React 的 State 仍是 "",登入按鈕就維持 disabled,使用者無法點擊。

2. 結合 CSS @keyframes 與 onAnimationStart 偵測自動填入狀態

要讓元件在載入時就得知欄位已被預填,可以利用瀏覽器套用 :-webkit-autofill / :autofill 的瞬間觸發一個極短的 CSS @keyframes 動畫:元素套用新的 animation-name 時動畫開始並派發 animationstart 事件,React 以 onAnimationStart 監聽:

/* 定義用來通知 JavaScript 自動填入開始與取消的空白動畫(使用合法的 opacity 屬性) */
@keyframes onAutoFillStart {
  from { opacity: 0.99; }
  to { opacity: 1; }
}

@keyframes onAutoFillCancel {
  from { opacity: 0.99; }
  to { opacity: 1; }
}

/* 當欄位進入自動填入狀態時,觸發 onAutoFillStart */
input:-webkit-autofill {
  animation-name: onAutoFillStart;
  animation-duration: 0.001s;
}

input:autofill {
  animation-name: onAutoFillStart;
  animation-duration: 0.001s;
}

/* 當欄位離開自動填入狀態時,觸發 onAutoFillCancel */
input:not(:-webkit-autofill) {
  animation-name: onAutoFillCancel;
  animation-duration: 0.001s;
}

接著在 React 登入元件中同時監聽 onChange 與 onAnimationStart:

import { useState } from 'react';

export default function LoginForm() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [isBrowserAutofilled, setIsBrowserAutofilled] = useState(false);

  const handleAnimationStart = (event) => {
    if (event.animationName === 'onAutoFillStart') {
      setIsBrowserAutofilled(true);
      // 若使用者已互動過,event.target.value 會有值,可同步寫入 State
      if (event.target.value) {
        if (event.target.name === 'username') setUsername(event.target.value);
        if (event.target.name === 'password') setPassword(event.target.value);
      }
    } else if (event.animationName === 'onAutoFillCancel') {
      setIsBrowserAutofilled(false);
    }
  };

  // 只要使用者手動輸入完畢,或是瀏覽器已處於預填狀態,皆允許點擊登入按鈕
  const canSubmit = (username.length > 0 && password.length > 0) || isBrowserAutofilled;

  return (
    <form method="POST" action="/api/login">
      <div className="form-field">
        <label htmlFor="login-user">帳號</label>
        <input
          type="text"
          id="login-user"
          name="username"
          autoComplete="username"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          onAnimationStart={handleAnimationStart}
          required
        />
      </div>

      <div className="form-field">
        <label htmlFor="login-pass">密碼</label>
        <input
          type="password"
          id="login-pass"
          name="password"
          autoComplete="current-password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          onAnimationStart={handleAnimationStart}
          required
        />
      </div>

      <button type="submit" disabled={!canSubmit}>
        登入
      </button>
    </form>
  );
}

這樣即使 input.value 還是空字串,isBrowserAutofilled 也會在欄位進入自動填入狀態時變為 true,登入按鈕保持可點擊;使用者第一次互動時,Chrome 把預填值寫入欄位並派發 input 與 change 事件,onChange 隨之更新 State。


五、總結

  1. 視覺::-webkit-autofill 與 :autofill 拆成獨立規則,搭配內陰影、-webkit-text-fill-color、caret-color。
  2. 語意:一般查詢框用 off;後台新增員工、重設密碼等欄位改用 new-password。
  3. 狀態:互動前 input.value 是空字串,不要用它鎖死提交按鈕,改用 animationstart 同步框架狀態。

游標消失、預覽字型、Honeypot 誤填與 200 欄位上限,見 HTML input 自動填入進階排查。

參考資料與延伸閱讀

發佈留言