D 的个人博客

但行好事莫问前程

  menu
417 文章
3446695 浏览
9 当前访客
ღゝ◡╹)ノ❤️

禁止浏览器自动填充表单字段

###场景

我们的登录表单一般都是 input text + input password:

1<form id="loginForm">
2    <input type="text" name="username">
3    <input type="password" name="password">
4    <button type="submit">登录</button>
5</form>

登录后如果用户选择了保存登录密码,那后续界面中如果有形如:

1<input type="text" name="field1">
2<input type="password" name="field2">

这样的两个 input(text+password)接在一起,那浏览器就会自动填充登录时的输入。

要用程序清空自动填充有两个方案:

###使用 autocomplete 属性

在不需要自动填充的 input 上设置 autocomplete 属性:

1<input autocomplete="off">

这个方案对于某些版本的浏览器可能不行。

###使用假的 input 让浏览器去填充

在页面 <body> 后加入:

1<!-- fake fields are a workaround for chrome autofill getting the wrong fields -->
2<input style="display:none" type="text" name="fakeusernameremembered"/>
3<input style="display:none" type="password" name="fakepasswordremembered"/>

这个方案原理是让浏览器去填充用户实际上看不到的 input。虽然看上去代码比较 low,但是很实用。

参考:Disabling Chrome Autofill