如何禁止浏览器自动填充

本文由 Deguang 发表于 码路-技术博客html

浏览器的保存帐户密码功能,给咱们带来了很大的便利,可是在有些状况下,咱们并不但愿浏览器帮咱们填充一些表单,然而autocomplete的一些参数项并不能阻止浏览器回填,这里咱们来看下如何解决这个问题。

问题描述:

项目注册部分的表单有三项,分别为手机号验证码密码,当完成注册操做后,浏览器提醒是否保存密码,用户名部分显示的是验证码,点击保存后,打开登陆页面,手机号密码项被分别填充为了验证码密码,给用户带来了必定的不便。浏览器

解决过程:

1. 第一反应考虑到的是,给登陆表单的<input>标签,增长autocomplete="off"app

MDN autocomplate 文档ide

"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.ui

  • 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 值不能阻止浏览器的密码管理工具自动填充,因此第一次尝试失败;this

2. 动态设置密码 input 标签 typeurl

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

这样设置 能够保证用户在点击密码框以前,避免浏览器识别为登陆表单、自动填充。code

这里多说两句,浏览器是如何判断当前表单须要 autocomplete,浏览器自动保存表单是当前 form 存在 type 为 password 的input、且该 input 为表单中的第二个 input 输入框。

因此,这里给 password 设置初始 type 为 text,在用户 点击 input 聚焦后 设置 type 为 password ,避免浏览器在 页面 onload 以后判断登陆表单进行回填。这样能够解决大部分场景下对于避免回填的须要。然而咱们的业务须要 依据跳转连接中的 param 给用户填充 密码,这就致使了在用户 主动 focus 以前,密码会被明文展现,聚焦后又会隐藏,操做体验不佳;orm

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 为一个 任意字符串 ,也能达到相同效果,你们能够试一下)

相关文章
相关标签/搜索