How to Check if a Website is Focused

Updated

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();
1
2const onFocus = () => {
3    isFocused = true
4};
5const onBlur = () => {
6    isFocused = false
7}
8
9window.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);
1
2useEffect(() => {
3    const onFocus = () => setIsFocused(true);
4    const onBlur = () => setIsFocused(false);
5
6    window.addEventListener('focus', onFocus);
7    window.addEventListener('blur', onBlur);
8
9    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.