Detecting Browser Autofill

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

    If you only want to detect whether auto-fill has been used or not, rather than detecting exactly when and to which field auto-fill has been used, you can simply add a hidden element that will be auto-filled and then check whether this contains any value. I understand that this may not be what many people are interested in. Set the input field with a negative tabIndex and with absolute coordinates well off the screen. It's important that the input is part of the same form as the rest of the input. You must use a name that will be picked up by Auto-fill (ex. "secondname").

    var autofilldetect = document.createElement('input');
    autofilldetect.style.position = 'absolute';
    autofilldetect.style.top = '-100em';
    autofilldetect.style.left = '-100em';
    autofilldetect.type = 'text';
    autofilldetect.name = 'secondname';
    autofilldetect.tabIndex = '-1';
    

    Append this input to the form and check its value on form submit.

提交回复
热议问题