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

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

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

if (autoFilled == true) {

} else {

}

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

可能重复

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

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

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


当前回答

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

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

其他回答

对于谷歌chrome自动完成,这为我工作:

if ($("#textbox").is(":-webkit-autofill")) 
{    
    // the value in the input field of the form was filled in with google chrome autocomplete
}

不幸的是,我发现唯一可靠的方法来检查这个跨浏览器是轮询输入。为了使它具有响应性,还需要侦听事件。 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); });

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

bower install autofill-event

从我个人的经验来看,下面的代码在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();
});

在Chrome和Edge(2020)中检查:-webkit-autofill会告诉你输入已经填充。但是,在用户以某种方式与页面交互之前,JavaScript无法获得输入中的值。

使用$('x').focus()和$('x').blur()或在代码中触发鼠标事件都没有帮助。

参见https://stackoverflow.com/a/35783761/32429