Detecting Browser Autofill

前端 未结 29 1989
天涯浪人
天涯浪人 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 07:01

    To detect email for example, I tried "on change" and a mutation observer, neither worked. setInterval works well with LinkedIn auto-fill (not revealing all my code, but you get the idea) and it plays nice with the backend if you add extra conditions here to slow down the AJAX. And if there's no change in the form field, like they're not typing to edit their email, the lastEmail prevents pointless AJAX pings.

    // lastEmail needs scope outside of setInterval for persistence.
    var lastEmail = 'nobody';
    window.setInterval(function() { // Auto-fill detection is hard.
        var theEmail = $("#email-input").val();
        if (
            ( theEmail.includes("@") ) &&
            ( theEmail != lastEmail )
        ) {
            lastEmail = theEmail;
            // Do some AJAX
        }
    }, 1000); // Check the field every 1 second
    

提交回复
热议问题