Detecting Browser Autofill

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

    Unfortunately the only reliable way i have found to check this cross browser is to poll the input. To make it responsive also listen to events. Chrome has started hiding auto fill values from javascript which needs a 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);
      });
      

提交回复
热议问题