Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sobstel
Last active September 30, 2022 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sobstel/ff27eee6cc1279812ff2c9689e7467b7 to your computer and use it in GitHub Desktop.
Save sobstel/ff27eee6cc1279812ff2c9689e7467b7 to your computer and use it in GitHub Desktop.
React: handle browser-autofilled password in Chrome
// Problem: when remembered, Chrome auto-fills the password input, but in fact it doesn't
// set the value and doesn't fire onChange event until there's any kind of interaction.
// If password value is empty, then submit button is still disabled yet password looks filled,
// which looks bad. See: https://bugs.chromium.org/p/chromium/issues/detail?id=813175
const [isAutofilled, setIsAutofilled] = useState(false);
const passwordElRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
const element = passwordElRef.current;
let timeoutId: ReturnType<typeof setTimeout> | null = null;
const handleAutofill = () => {
const isSecretlyFilledByBrowser = !password && Boolean(element?.matches('*:-webkit-autofill'));
setIsAutofilled(isSecretlyFilledByBrowser);
if (!isSecretlyFilledByBrowser && !password) {
timeoutId = setTimeout(handleAutofill, 500);
}
}
handleAutofill();
return () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
};
}, [passwordElRef, password]);
<input ref={passwordElRef} value={password} />
<input type="submit" disabled={!isAutofilled && !password} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment