如何判断浏览器是否已自动填充文本框?特别是用户名和密码框,自动填充页面加载。

我的第一个问题是,这在页面加载序列中什么时候发生?是在document.ready之前还是之后?

其次,我如何使用逻辑来找出是否发生了这种情况?这不是我想阻止这种情况发生,只是挂钩到事件。最好是这样的:

if (autoFilled == true) {

} else {

}

如果可能的话,我很想看到一个jsfiddle显示你的答案。

可能重复

DOM事件浏览器密码自动填充?

浏览器自动填充和Javascript触发事件

这两个问题都没有真正解释什么事件被触发,它们只是不断地重新检查文本框(对性能不好!)


当前回答

似乎有一个解决方案,不依赖轮询(至少Chrome)。它几乎是一样的粗鄙,但我确实认为比全球民意调查好一点。

考虑以下场景:

用户开始填写字段1 用户选择一个自动完成建议,自动填充field2和field3

解决方案:在所有字段上注册一个onblur,通过下面的jQuery片段$(':-webkit-autofill')检查自动填充字段的存在

这不会是立即的,因为它会延迟到用户模糊field1,但它不依赖于全局轮询,所以在我看来,这是一个更好的解决方案。

也就是说,由于按回车键可以提交表单,您可能还需要相应的onkeypress处理程序。

或者,你可以使用全局轮询来检查$(':-webkit-autofill')

其他回答

在2020年,这是我在chrome中工作的方法:

// wait 0.1 sec to execute action after detecting autofill
// check if input username is autofilled by browser
// enable "login" button for click to submit form
 $(window).on("load", function(){
       setTimeout(function(){

           if ($("#UserName").is("input:-webkit-autofill")) 
           $("#loginbtn").prop('disabled', false); 

      }, 100);
 });

从我个人的经验来看,下面的代码在firefox IE和safari中工作得很好,但在chrome中选择自动完成时工作得不太好。

function check(){
clearTimeout(timeObj);
 timeObj = setTimeout(function(){
   if($('#email').val()){
    //do something
   }
 },1500);
}

$('#email').bind('focus change blur',function(){
 check();
});

下面的代码工作得更好,因为它会触发每次用户点击输入字段,从那里你可以检查输入字段是否为空。

$('#email').bind('click', function(){
 check();
});

问题是不同的浏览器处理自动填充的方式不同。有些调度变更事件,有些则不调度。因此,当浏览器自动完成一个输入字段时,几乎不可能钩到一个事件。

更改不同浏览器的事件触发器: 对于用户名/密码字段: Firefox 4、IE 7和IE 8不分派更改事件。 Safari 5和Chrome 9会分派更改事件。 对于其他表单字段: ie7和ie8不分派变更事件。 当用户从建议列表中选择一个值并从字段中选择tab时,Firefox 4会分派change change事件。 Chrome 9不会分派更改事件。 Safari 5确实分派了更改事件。

你最好的选择是在你的表单中使用autocomplete="off"来禁用表单的自动完成功能,或者定期轮询查看它是否已填充。

关于你问的是在文件上还是之前填写的问题。不同浏览器,甚至不同版本都不一样。对于用户名/密码字段,仅当您选择用户名时才填写密码字段。因此,如果你试图附加到任何事件,你会有一个非常混乱的代码。

你可以在这里好好阅读一下

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';

将此输入附加到表单,并在表单提交时检查其值。

我知道这是一个老话题,但我可以想象很多人来这里寻找解决方案。

要做到这一点,你可以检查输入(s)是否有值(s):

$(function() {
    setTimeout(function() {
        if ($("#inputID").val().length > 0) {
            // YOUR CODE
        }
    }, 100);
});

当我的登录表单被加载以启用提交按钮时,我自己就用它来检查登录表单中的值。 代码是为jQuery编写的,但是如果需要的话很容易更改。