如何在主要浏览器中禁用特定输入(或表单字段)的自动完成?
当前回答
我遇到了同样的问题,今天2019年10月9日,我找到的唯一解决方案是
将autocomplete=“off”添加到表单标记中。
打开表单标签后输入1个错误。
<input id="username" style="display:none" type="text" name="fakeusernameremembered">
但它在密码类型字段上不起作用,请尝试
<input type="text" oninput="turnOnPasswordStyle()" placeholder="Enter Password" name="password" id="password" required>
在脚本上
function turnOnPasswordStyle() {
$('#password').attr('type', "password");
}
这在Chrome-78、IE-44、Firefox-69上进行了测试
其他回答
目前我找到的解决方案都没有带来真正有效的回应。
具有自动完成属性的解决方案不起作用。
所以,这是我为自己写的:
<input type="text" name="UserName" onkeyup="if (this.value.length > 0) this.setAttribute('type', 'password'); else this.setAttribute('type', 'text');" >
您应该对页面上希望作为密码类型的每个输入字段执行此操作。
这是有效的。
干杯
由于自动完成的行为在不同的浏览器和版本中几乎是不可预测的,所以我的方法是不同的。指定要禁用只读属性自动填充的所有输入元素,并仅在聚焦时禁用它。
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属性作为回退。
将输入保留为文本类型并隐藏。在DOMContentLoaded上,调用一个函数来更改密码类型并显示字段,延迟1秒。
document.addEventListener('DOMContentLoaded',changeInputsType);函数更改InputsType(){setTimeout(函数){$(/*selector*/).prop(“type”,“password”).show();}, 1000);}
Chrome计划支持这一点。
目前,最好的建议是使用很少自动完成的输入类型。
Chrome讨论
<input type='search' name="whatever" />
要与Firefox兼容,请使用normalautocomplete='off'
<input type='search' name="whatever" autocomplete='off' />
截至2019年12月:
在回答这个问题之前,让我说,我在SO和不同论坛上尝试了几乎所有的答案,但没有找到适用于所有现代浏览器和IE11的解决方案。
这是我找到的解决方案,我相信这篇文章中还没有讨论或提及。
根据Mozilla开发网络(MDN)关于如何关闭表单自动完成的帖子
默认情况下,浏览器会记住用户通过网站上的字段提交的信息。这使浏览器能够提供自动补全(即,为用户已开始键入的字段建议可能的补全)或自动填充(即,在加载时预先填充某些字段)
在同一篇文章中,他们讨论了自动完成属性的用法及其限制。正如我们所知,并不是所有的浏览器都按照我们的意愿来尊重这个属性。
解决方案
所以在文章的最后,他们分享了一个适用于所有浏览器的解决方案,包括IE11+Edge。它基本上是一个jQuery插件。这里是jQuery插件的链接及其工作原理。
代码段:
$(document).ready(function () {
$('#frmLogin').disableAutoFill({
passwordField: '.password'
});
});
在HTML中需要注意的是,密码字段的类型为文本,并应用密码类来标识该字段:
<input id="Password" name="Password" type="text" class="form-control password">
希望这能对某人有所帮助。