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

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

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

if (autoFilled == true) {

} else {

}

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

可能重复

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

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

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


当前回答

$('selector').on('keyup', aFunction);
// If tab is active, auto focus for trigger event keyup, blur, change...
// for inputs has been autofill
$(window).on('load', () => {
  if (!document.hidden) {
    window.focus();
  }
})

这对我很有用。 在Chrome上测试。

其他回答

这里有一个技巧来理解浏览器是否填充输入(布尔):

const inputEl = inputRef.current; // select the el with any way, here is ReactJs ref
let hasValue;
try {
  hasValue = inputRef.current.matches(':autofill');
} catch (err) {
  try {
    hasValue = inputRef.current.matches(':-webkit-autofill');
  } catch (er) {
    hasValue = false;
  }
}

// hasValue (boolean) is ready

在最后一个大括号之后,hasValue就可以使用了。您可以检测浏览器是否发生了自动填充。

我在最新的Firefox、Chrome和Edge浏览器上都能使用这种方法:

$('#email').on('blur input', function() {
    ....
});

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

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

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

对我来说没问题。

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

我的解决方案:

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

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

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