如何判断浏览器是否已自动填充文本框?特别是用户名和密码框,自动填充页面加载。
我的第一个问题是,这在页面加载序列中什么时候发生?是在document.ready之前还是之后?
其次,我如何使用逻辑来找出是否发生了这种情况?这不是我想阻止这种情况发生,只是挂钩到事件。最好是这样的:
if (autoFilled == true) {
} else {
}
如果可能的话,我很想看到一个jsfiddle显示你的答案。
可能重复
DOM事件浏览器密码自动填充?
浏览器自动填充和Javascript触发事件
这两个问题都没有真正解释什么事件被触发,它们只是不断地重新检查文本框(对性能不好!)
不幸的是,我发现唯一可靠的方法来检查这个跨浏览器是轮询输入。为了使它具有响应性,还需要侦听事件。
Chrome已经开始隐藏javascript的自动填充值,这需要一个hack。
Poll every half to third of a second ( Does not need to be instant in most cases )
Trigger the change event using JQuery then do your logic in a function listening to the change event.
Add a fix for Chrome hidden autofill password values.
$(document).ready(function () {
$('#inputID').change(YOURFUNCTIONNAME);
$('#inputID').keypress(YOURFUNCTIONNAME);
$('#inputID').keyup(YOURFUNCTIONNAME);
$('#inputID').blur(YOURFUNCTIONNAME);
$('#inputID').focusin(YOURFUNCTIONNAME);
$('#inputID').focusout(YOURFUNCTIONNAME);
$('#inputID').on('input', YOURFUNCTIONNAME);
$('#inputID').on('textInput', YOURFUNCTIONNAME);
$('#inputID').on('reset', YOURFUNCTIONNAME);
window.setInterval(function() {
var hasValue = $("#inputID").val().length > 0;//Normal
if(!hasValue){
hasValue = $("#inputID:-webkit-autofill").length > 0;//Chrome
}
if (hasValue) {
$('#inputID').trigger('change');
}
}, 333);
});
If you only want to detect whether auto-fill has been used or not, rather than detecting exactly when and to which field auto-fill has been used, you can simply add a hidden element that will be auto-filled and then check whether this contains any value. I understand that this may not be what many people are interested in. Set the input field with a negative tabIndex and with absolute coordinates well off the screen. It's important that the input is part of the same form as the rest of the input. You must use a name that will be picked up by Auto-fill (ex. "secondname").
var autofilldetect = document.createElement('input');
autofilldetect.style.position = 'absolute';
autofilldetect.style.top = '-100em';
autofilldetect.style.left = '-100em';
autofilldetect.type = 'text';
autofilldetect.name = 'secondname';
autofilldetect.tabIndex = '-1';
将此输入附加到表单,并在表单提交时检查其值。