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

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

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

if (autoFilled == true) {

} else {

}

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

可能重复

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

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

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


当前回答

我读了很多关于这个问题的文章,想提供一个非常快速的解决方法来帮助我。

let style = window.getComputedStyle(document.getElementById('email'))
  if (style && style.backgroundColor !== inputBackgroundNormalState) {
    this.inputAutofilledByBrowser = true
  }

我的模板的inputBackgroundNormalState是'rgb(255,255,255)'。

所以基本上当浏览器应用自动补全时,他们倾向于通过在输入上应用不同的(烦人的)黄色来指示输入是自动填充的。

编辑:这适用于所有浏览器

其他回答

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

在github上有一个新的polyfill组件来解决这个问题。看看autofill-event。只需要安装它和voilà,自动填充工作如预期。

bower install autofill-event

我的解决方案:

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

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

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

我为angularjs找到了一个有效的解决方案。

诀窍是在以下情况下禁用输入字段的required属性 该指令检测字段是由浏览器通过自动填充填充的。

由于不再需要输入字段,登录提交按钮将被启用。

这即使用户没有点击进入窗口的主体(见Chrome自动填充/自动完成无值密码)。

指令:

angular.module('formtools').directive('autofill', [
        '$interval', function ($interval)
        {
            return {
                scope: false,
                require: 'autofill',
                controller: function AutoFillController(){
                    this.applied = false;
                },
                controllerAs: 'autoFill',
                link: function (scope, elem, attrs, autofill)
                {
                    var refresh = $interval(function() {
                        // attention: this needs jquery, jqlite from angular doesn't provide this method
                        if(elem.is(':-webkit-autofill'))
                        {
                            autofill.applied = true;
                            $interval.cancel(refresh);
                        }
                    }, 100, 100);
                }
            }
        }]);

HTML:

<form name="loginform">

  <input 
     type="text" 
     name="username" 
     autofill 
     ng-required="!autoFill.applied">
  
  <input 
     type="password" 
     name="password" 
     autofill 
     ng-required="!autoFill.applied">
     
  <button ng-disabled="loginform.$invalid">Login</button>   
</form>

WebKit浏览器的解决方案

来自MDN文档:-webkit-autofill CSS伪类:

当一个元素的值被浏览器自动填充时,CSS伪类就会匹配

我们可以在<input>元素为:-webkit-autofill时定义一个void transition css规则。JS将能够钩到animationstart事件。

感谢Klarna UI团队。这里可以看到它们的实现:

CSS规则 JS钩