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

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

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

if (autoFilled == true) {

} else {

}

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

可能重复

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

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

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


当前回答

下面是来自Klarna UI团队的CSS解决方案。参见它们的出色实现

对我来说没问题。

input:-webkit-autofill {
  animation-name: onAutoFillStart;
  transition: background-color 50000s ease-in-out 0s;
}
input:not(:-webkit-autofill) {
  animation-name: onAutoFillCancel;
}

其他回答

经过研究发现,webkit浏览器在自动完成时不会触发更改事件。我的解决方案是自己获取webkit添加的自动填充类并触发更改事件。

setTimeout(function() {
 if($('input:-webkit-autofill').length > 0) {
   //do some stuff
 }
},300)

这里是一个链接的问题在铬。https://bugs.chromium.org/p/chromium/issues/detail?id=636425

我用这个方法来解决同样的问题。

HTML代码应该改为这样:

<input type="text" name="username" />
<input type="text" name="password" id="txt_password" />

jQuery代码应该在document.ready中:

$('#txt_password').focus(function(){
    $(this).attr('type','password');
});

我在使用Instagram自动填充电子邮件和电话输入时遇到了这个问题,尝试了不同的解决方案,但没有任何效果。最后,我所要做的就是禁用自动填充,为电话和电子邮件设置不同的名称属性。

在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);
 });

我的解决方案:

像往常一样监听更改事件,并在DOM内容加载上执行以下操作:

setTimeout(function() {
    $('input').each(function() {
        var elem = $(this);
        if (elem.val()) elem.change();
    })
}, 250);

这将在用户有机会编辑所有非空字段之前触发更改事件。