| 需求 | 方案 | 優缺點 |
|---|---|---|
| 阻止瀏覽器「保存密碼」彈窗 | 隱藏誘餌字段 / `autocomplete="off"` / 隨機 name 屬性 | 瀏覽器策略不一,可能失效 |
| 實現類密碼框效果(黑點掩碼) | `input[type=password]` 原生 / `font-family: text-security-disc` / 自定義組件 | 原生最安全、兼容好 |
<form>
<!-- 瀏覽器會優先填充第一個 password 類型字段 -->
<input type="password" style="display:none" aria-hidden="true">
<!-- 真實用戶名 -->
<input type="text" name="username" autocomplete="username">
<!-- 真實密碼 -->
<input type="password" name="password" autocomplete="current-password">
</form>
<input type="text" id="pwd" name="password" autocomplete="new-password">
<script>
document.getElementById('pwd').addEventListener('focus', function() {
this.type = 'password'; // 聚焦時切為密碼模式
});
</script>
若堅持不用 `type=password`,需自行實現:
<style>
.secure-input {
font-family: 'text-security-disc'; // 原生掩碼字體
-webkit-text-security: disc; // WebKit 內核
}
</style>
<input type="text" class="secure-input" id="fakePwd">
<script>
// 同步真實值到隱藏字段
const realPwd = document.createElement('input');
realPwd.type = 'hidden';
realPwd.name = 'password';
document.body.appendChild(realPwd);
document.getElementById('fakePwd').addEventListener('input', function() {
realPwd.value = this.value;
// 可選:光標位置同步、選中狀態同步等複雜邏輯
});
</script>
<form>
<input type="text" name="username" autocomplete="username" required>
<input type="password" name="password" autocomplete="current-password" required>
<!-- 新密碼註冊/修改頁面用 autocomplete="new-password" -->
<button type="submit">登錄</button>
</form>
配合 HTTPS、CSP、SameSite Cookie,才是真正的安全基線。