'Chrome: alert during onfocus creates an infinite loop?
I was trying to figure out how to get some focus/blur behavior working for something when I ran into a really strange and annoying behavior in the Chrome debugger where I got an infinite loop while trying to debug an onfocus
handler. It seems to be related to any action which takes focus away as I've been able to reproduce it using alerts instead of a breakpoint.
Here is my minimal example. Make sure you open this in another tab. Closing the tab is the only way I've found to end the loop.
https://codepen.io/cebo494/pen/OJxVZxq
Is this a known issue? Is there an easy workaround other than just using print statements to debug everything?
My final goal in my actual handlers isn't to take away focus, so it's not a problem if this is just a bad practice that I should avoid, but it's super annoying not being able to use the chrome debugger for my focus callbacks.
This seems to be specifically a Chrome issue, as the loop didn't occur in Firefox or IE. It only happens in Chrome and Edge (which is chromium)
Solution 1:[1]
I tried the sandbox, it actually got triggered on Firefox as well. I think the problem is that when you close the alert, the focus is lost on the button, but React internally re-focus on the button again, therefore trigger another onFocus call.
I would set a flag to manage the alert behavior, and reset the flag during onBlur event:
const [alert, setAlert] = useState(false);
// you can also pass event to implement the onblur method in the same function
const alertInfo = () => {
if (!alert) {
alert("focus");
setAlert(true);
}
}
Or if the event is only triggered by mouse, you can also use onmouseup/onmousedown to handle the event.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | GoldenArcher |