Last active
September 30, 2022 09:26
-
-
Save sobstel/ff27eee6cc1279812ff2c9689e7467b7 to your computer and use it in GitHub Desktop.
React: handle browser-autofilled password in Chrome
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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