如何禁止瀏覽器自動填充


本文由 Deguang 發表於 碼路-技術博客

瀏覽器的保存賬戶密碼功能,給我們帶來了很大的便利,但是在有些情況下,我們並不希望瀏覽器幫我們填充一些表單,然而autocomplete的一些參數項並不能阻止瀏覽器回填,這里我們來看下如何解決這個問題。

問題描述:

項目注冊部分的表單有三項,分別為手機號驗證碼密碼,當完成注冊操作后,瀏覽器提醒是否保存密碼,用戶名部分顯示的是驗證碼,點擊保存后,打開登錄頁面,手機號密碼項被分別填充為了驗證碼密碼,給用戶帶來了一定的不便。

解決過程:

1. 第一反應考慮到的是,給登錄表單的<input>標簽,增加autocomplete="off"

MDN autocomplate 文檔

"off"

  • The browser is not permitted to automatically enter or select a value for this field. It is possible that the

document or application provides its own autocomplete feature, or that security concerns require that the
field's value not be automatically entered.

  • Note: In most modern browsers, setting autocomplete to "off" will not prevent a password manager from asking the user if they would like to save username and password information, or from automatically filling in those values in a site's login form. See the autocomplete attribute and login fields.

在autocomplete的文檔中說明了value為off時,瀏覽器禁止給當前字段自動的輸入或者選中一個值,但下方Note言明:在大多數現代瀏覽器中,off 值不能阻止瀏覽器的密碼管理工具自動填充,所以第一次嘗試失敗;

2. 動態設置密碼 input 標簽 type

<input type="text" onfocus="this.type='password'"></input>

這樣設置 可以保證用戶在點擊密碼框之前,避免瀏覽器識別為登錄表單、自動填充。

這里多說兩句,瀏覽器是如何判斷當前表單需要 autocomplete,瀏覽器自動保存表單是當前 form 存在 type 為 password 的input、且該 input 為表單中的第二個 input 輸入框。

所以,這里給 password 設置初始 type 為 text,在用戶 點擊 input 聚焦后 設置 type 為 password ,避免瀏覽器在 頁面 onload 之后判斷登錄表單進行回填。這樣可以解決大部分場景下對於避免回填的需要。然而我們的業務需要 依據跳轉鏈接中的 param 給用戶填充 密碼,這就導致了在用戶 主動 focus 之前,密碼會被明文展示,聚焦后又會隱藏,操作體驗不佳;

3. page.onload 后 js 控制 input type
方法同上,問題點在於 頁面load 后手動設置 input type 為 password,而后根據 page url 參數 填充表單。

但存在問題是 瀏覽器填充的時機無法控制,導致業務填充表單被自動填充覆蓋;方案pass;

4. autocomplete 設置 其他參數

autocomplete 除了 on、off 之外,還有很多參數:name、email、username、new-password、current-password、street-address 等等;

當 input type 為 password 但 autocomplete 為 new-password, 即可解決瀏覽器自動填充問題,瀏覽器將當前輸入框識別為新密碼,便不會自阿東填充值。(PS:有例子提到,設置 autocomplete 為一個 任意字符串 ,也能達到相同效果,大家可以試一下)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM