Detecting Browser Autofill

2018-12-31 13:45发布

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 this occur in the page load sequence? Is it before or after document.ready?

Secondly how can I use logic to find out if this occurred? Its not that i want to stop this from occurring, just hook into the event. Preferably something like this:

if (autoFilled == true) {

} else {

}

If possible I would love to see a jsfiddle showing your answer.

Possible duplicates

DOM event for browser password autofill?

Browser Autofill and Javascript triggered events

--Both these questions don't really explain what events are triggered, they just continuously recheck the text-box (not good for performance!).

26条回答
几人难应
2楼-- · 2018-12-31 14:08

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:

<form action="#" method="POST" class="js-filled_check">

    <fieldset>

        <label for="test_username">Test username:</label>
        <input type="text" id="test_username" name="test_username" value="">

        <label for="test_password">Test password:</label>
        <input type="password" id="test_password" name="test_password" value="">

        <button type="submit" name="test_submit">Test submit</button>

    </fieldset>

</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!

查看更多
长期被迫恋爱
3楼-- · 2018-12-31 14:10

Just in case someone is looking for a solution (just as I was today), to listen to a browser autofill change, here's a custom jquery method that I've built, just to simplify the proccess when adding a change listener to an input:

    $.fn.allchange = function (callback) {
        var me = this;
        var last = "";
        var infunc = function () {
            var text = $(me).val();
            if (text != last) {
                last = text;
                callback();
            }
            setTimeout(infunc, 100);
        }
        setTimeout(infunc, 100);
    };

You can call it like this:

$("#myInput").allchange(function () {
    alert("change!");
});
查看更多
旧时光的记忆
4楼-- · 2018-12-31 14:10

I know this is an old thread but I can imagine many comes to find a solution to this here.

To do this, you can check if the input(s) has value(s) with:

$(function() {
    setTimeout(function() {
        if ($("#inputID").val().length > 0) {
            // YOUR CODE
        }
    }, 100);
});

I use this myself to check for values in my login form when it's loaded to enable the submit button. The code is made for jQuery but is easy to change if needed.

查看更多
只靠听说
5楼-- · 2018-12-31 14:10

There does appear to be a solution to this that does not rely on polling (at least for Chrome). It is almost as hackish, but I do think is marginally better than global polling.

Consider the following scenario:

  1. User starts to fill out field1

  2. User selects an autocomplete suggestion which autofills field2 and field3

Solution: Register an onblur on all fields that checks for the presence of auto-filled fields via the following jQuery snippet $(':-webkit-autofill')

This won't be immediate since it will be delayed until the user blurs field1 but it doesn't rely on global polling so IMO, it is a better solution.

That said, since hitting the enter key can submit a form, you may also need a corresponding handler for onkeypress.

Alternately, you can use global polling to check $(':-webkit-autofill')

查看更多
妖精总统
6楼-- · 2018-12-31 14:14

My solution is:

    $.fn.onAutoFillEvent = function (callback) {
        var el = $(this),
            lastText = "",
            maxCheckCount = 10,
            checkCount = 0;

        (function infunc() {
            var text = el.val();

            if (text != lastText) {
                lastText = text;
                callback(el);
            }
            if (checkCount > maxCheckCount) {
                return false;
            }
            checkCount++;
            setTimeout(infunc, 100);
        }());
    };

  $(".group > input").each(function (i, element) {
      var el = $(element);

      el.onAutoFillEvent(
          function () {
              el.addClass('used');
          }
      );
  });
查看更多
素衣白纱
7楼-- · 2018-12-31 14:16

Solution for WebKit browsers

From the MDN docs for the :-webkit-autofill CSS pseudo-class:

The :-webkit-autofill CSS pseudo-class matches when an element has its value autofilled by the browser

We can define a void transition css rule on the desired <input> element once it is :-webkit-autofilled. JS will then be able to hook onto the animationstart event.

Credits to the Klarna UI team. See their nice implementation here:

查看更多
登录 后发表回答