How to resolve chrome autofill but JS cannot get input value until user interaction

Recently our company refator the login page and redesign the UI. As u can see in the below ,chrome has autofill the password feature, but u also can see though the email and password is not empty, but the login button is also still disabled. So it’s weired.

Here said this behavior is working as expected and mitigates a privacy/security attack,
values of auto-filled inputs on page load are not accessible through JS until a user interacts with a page.
https://bugs.chromium.org/p/chromium/issues/detail?id=1166619,
https://bugs.chromium.org/p/chromium/issues/detail?id=163072

So then we need find a workaround about the behavior, and we find window.getComputedStyle(element, null).getPropertyValue('appearance') the value is menulist-button, so the we can from here to find a hack solution.

Detect the button is filled or not:

1
2
3
4
5
6
7
8
9
10
11
const detectAutofill = (element: HTMLBaseElement): Promise<boolean> =>

new Promise((resolve) => {

setTimeout(() => {

resolve(window.getComputedStyle(element, null).getPropertyValue('appearance') === 'menulist-button');

}, 600);

});

Then we need add a variable to enable the submit button if the value is true:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const [isPasswordAutoFilled, setIsPasswordAutoFilled] = useState(false); // for enable the submit button

const passwordEl = useRef(null); // put the ref on password element

useEffect(() => {

const checkAutoFill = async () => {

const passwordFilled = await detectAutofill(passwordEl.current);

// if the password is auto filled by chrome, then we set the value to the state.
setIsPasswordAutoFilled(passwordFilled);

};

checkAutoFill();

}, [password]);

Finally in submit we can add a retry to make sure the login success rate.

1
2
3
4
5
// then we can add a retry `variable` to retry again and limit the times max 2
if (!password && retry !== true) {
setTimeout(() => submit(e, true), 100); // waiting for trigger next submit
return false
}

Though we do a hack for this improvement, but we don’t have fully confidence to make sure the code is normal work, so we add some GA tracking in the code and log the related error information, the result is the code work as expected.


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!