如何在主要浏览器中禁用特定输入(或表单字段)的自动完成?


当前回答

我认为HTML5支持autocomplete=off。

问问自己为什么要这样做——在某些情况下这可能是有意义的,但不要只是为了这样做而这样做。

这对用户来说不太方便,甚至在OS X中也没有安全问题(Soren在下面提到)。如果你担心人们的密码被远程窃取,即使你的应用程序使用autcomplete=off,击键记录器仍然可以做到这一点。

作为一个选择让浏览器记住(大部分)我的信息的用户,如果你的网站不记得我的信息,我会觉得很烦人。

其他回答

Firefox 30忽略密码的autocomplete=“off”,而是选择提示用户密码是否应存储在客户端上。请注意2014年5月5日的以下评论:

密码管理器始终提示是否要保存密码。未经用户许可,密码不会保存。我们是继IE和Chrome之后第三个实现这一改变的浏览器。

根据Mozilla开发者网络文档,布尔表单元素属性autocomplete防止表单数据在旧浏览器中缓存。

<input type="text" name="foo" autocomplete="off" />

我通过添加两个假输入并赋予它们绝对位置来阻止Chrome 66自动填充:

<form style="position: relative">
  <div style="position: absolute; top: -999px; left: -999px;">
    <input name="username" type="text" />
    <input name="password" type="password" />
  </div>
  <input name="username" type="text" />
  <input name="password" type="password" />

起初,我尝试添加display:none;但Chrome忽略了这些输入,并自动填充可见的输入。

由于自动完成的行为在不同的浏览器和版本中几乎是不可预测的,所以我的方法是不同的。指定要禁用只读属性自动填充的所有输入元素,并仅在聚焦时禁用它。

  document.addEventListener('click', (e) => {
    readOnlys.forEach(readOnly => {
      if (e.target == readOnly) {
        readOnly.removeAttribute('readonly', '');
        readOnly.style.setProperty('pointer-events', 'none');
      } else {
        readOnly.setAttribute('readonly', '');
        readOnly.style.setProperty('pointer-events', 'auto');
      }
    });
  });
  document.addEventListener('keyup', (e) => {
    if (e.key == 'Tab') {
      readOnlys.forEach(readOnly => {
        if (e.target == readOnly) {
          readOnly.removeAttribute('readonly', '');
          readOnly.style.setProperty('pointer-events', 'none');
        } else {
          readOnly.setAttribute('readonly', '');
          readOnly.style.setProperty('pointer-events', 'auto');
        }
      });
    }
  });

如果您想确保用户在禁用JS的情况下仍然可以访问字段,那么可以在页面加载时通过JS设置所有只读。您仍然可以使用autocomplete属性作为回退。

最佳解决方案:

防止自动完成用户名(或电子邮件)和密码:

<input type="email" name="email"><!-- Can be type="text" -->
<input type="password" name="password" autocomplete="new-password">

阻止自动完成字段:

<input type="text" name="field" autocomplete="nope">

说明:autocomplete在<input>中继续工作,autocomplete=“off”不工作,但您可以将off更改为随机字符串,如nope。

工作地点:

铬:49、50、51、52、53、54、55、56、57、58、59、60、61、62、63和64Firefox:44、45、46、47、48、49、50、51、52、53、54、55、56、57和58

对于React,您可以尝试将此代码放在表单下面或密码输入上面,或者放在电子邮件和密码输入之间

export const HackRemoveBrowsersAutofill = () => (
  <>
    <input type="email" autoComplete="new-password" style={ { display: 'none' } } />
    <input type="password" autoComplete="new-password" style={ { display: 'none' } } />
  </>
)

示例之一:

<input type="email"/>
<HackRemoveBrowsersAutofill/>
<input type="password"/>