How to Check if a Website is Focused
Updated at
When you want to check if a document / website is focused, to act accordingly, you can use the following snippet for vanilla javascript:
0 var isFocused = document.hasFocus();12const onFocus = () => {3 isFocused = true4};5const onBlur = () => {6 isFocused = false7}89window.addEventListener('focus', onFocus);10window.addEventListener('blur', onBlur);
If you want to use this in a react component you can use the following snippet:
0const [isFocused, setIsFocused] = useState(true);12useEffect(() => {3 const onFocus = () => setIsFocused(true);4 const onBlur = () => setIsFocused(false);56 window.addEventListener('focus', onFocus);7 window.addEventListener('blur', onBlur);89 return () => {10 window.removeEventListener('focus', onFocus);11 window.removeEventListener('blur', onBlur);12 };13}, []);
This way you can check if your website is focused and act accordingly. For example you can pause a video when the website is not focused. Or if you have a chat application you can show a notification when the website is not focused.