Detecting Browser Autofill

前端 未结 29 1770
天涯浪人
天涯浪人 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:49

    This is solution for browsers with webkit render engine. When the form is autofilled, the inputs will get pseudo class :-webkit-autofill- (f.e. input:-webkit-autofill {...}). So this is the identifier what you must check via JavaScript.

    Solution with some test form:

    And javascript:

    $(document).ready(function() {
    
        setTimeout(function() {
    
            $(".js-filled_check input:not([type=submit])").each(function (i, element) {
    
                var el = $(this),
                    autofilled = (el.is("*:-webkit-autofill")) ? el.addClass('auto_filled') : false;
    
                console.log("element: " + el.attr("id") + " // " + "autofilled: " + (el.is("*:-webkit-autofill")));
    
            });
    
        }, 200);
    
    });
    

    Problem when the page loads is get password value, even length. This is because browser's security. Also the timeout, it's because browser will fill form after some time sequence.

    This code will add class auto_filled to filled inputs. Also, I tried to check input type password value, or length, but it's worked just after some event on the page happened. So I tried trigger some event, but without success. For now this is my solution. Enjoy!

提交回复
热议问题