Detecting Browser Autofill

前端 未结 29 1807
天涯浪人
天涯浪人 2020-11-22 06:15

How do you tell if a browser has auto filled a text-box? Especially with username & password boxes that autofill around page load.

My first question is when does

29条回答
  •  无人共我
    2020-11-22 06:53

    I was looking for a similar thing. Chrome only... In my case the wrapper div needed to know if the input field was autofilled. So I could give it extra css just like Chrome does on the input field when it autofills it. By looking at all the answers above my combined solution was the following:

    /* 
     * make a function to use it in multiple places
     */
    var checkAutoFill = function(){
        $('input:-webkit-autofill').each(function(){
            $(this).closest('.input-wrapper').addClass('autofilled');
        });
    }
    
    /* 
     * Put it on the 'input' event 
     * (happens on every change in an input field)
     */
    $('html').on('input', function() {
        $('.input-wrapper').removeClass('autofilled');
        checkAutoFill();
    });
    
    /*
     * trigger it also inside a timeOut event 
     * (happens after chrome auto-filled fields on page-load)
     */
    setTimeout(function(){ 
        checkAutoFill();
    }, 0);
    

    The html for this to work would be

提交回复
热议问题