如何在主要浏览器中禁用特定输入(或表单字段)的自动完成?
当前回答
对于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"/>
其他回答
其想法是创建一个与原始字段同名的不可见字段。这将使浏览器自动填充隐藏字段。
我使用以下jQuery片段:
// Prevent input autocomplete
$.fn.preventAutocomplete = function() {
this.each(function () {
var $el = $(this);
$el
.clone(false, false) // Make a copy (except events)
.insertBefore($el) // Place it before original field
.prop('id', '') // Prevent ID duplicates
.hide() // Make it invisible for user
;
});
};
然后只需$(“#登录表单输入”).prpreventAutocomplete();
只需每次将输入元素中的name属性更改为唯一的属性,它就不会再次自动完成!
一个例子可能是结尾处添加的时间tic。您的服务器只需要解析文本名称的第一部分即可检索回值。
<input type="password" name="password_{DateTime.Now.Ticks}" value="" />
自动填充功能在不选择字段的情况下更改值。我们可以在状态管理中使用它来忽略选择事件之前的状态更改。
React中的一个示例:
import React, {Component} from 'react';
class NoAutoFillInput extends Component{
constructor() {
super();
this.state = {
locked: true
}
}
onChange(event){
if (!this.state.locked){
this.props.onChange(event.target.value);
}
}
render() {
let props = {...this.props, ...{onChange: this.onChange.bind(this)}, ...{onSelect: () => this.setState({locked: false})}};
return <input {...props}/>;
}
}
export default NoAutoFillInput;
如果浏览器尝试填充字段,则元素仍被锁定,状态不受影响。现在,您可以用NoAutoFillInput组件替换输入字段,以防止自动填充:
<div className="form-group row">
<div className="col-sm-2">
<NoAutoFillInput type="text" name="myUserName" className="form-control" placeholder="Username" value={this.state.userName} onChange={value => this.setState({userName: value})}/>
</div>
<div className="col-sm-2">
<NoAutoFillInput type="password" name="myPassword" className="form-control" placeholder="Password" value={this.state.password} onChange={value => this.setState({password: value})}/>
</div>
</div>
当然,这个想法也可以用于其他JavaScript框架。
这将解决此问题
autocomplete="new-password"
我已经在这场永无止境的战斗中战斗了很久。。。所有的技巧和黑客最终都会停止工作,就像浏览器开发人员正在阅读这个问题一样。
我不想随机化域名,不想修改服务器端代码,不想使用JS重磅技巧,也不想将“黑客攻击”降至最低。下面是我想到的:
TL;DR使用完全没有名称或id的输入!并跟踪隐藏字段中的更改
<!-- input without the "name" or "id" -->
<input type="text" oninput="this.nextElementSibling.value=this.value">
<input type="hidden" name="email" id="email">
显然,可以在所有主要浏览器中使用。
P.S.已知的小问题:
您不能再通过id或名称引用此字段。但您可以使用CSS类。或者使用$(#email').prev();在jQuery中。或者想出另一个解决方案(有很多)。当以编程方式更改文本框值时,oninput和onchange事件不会触发。因此,相应地修改代码以反映隐藏字段中的更改。