How to Check if a Website is Focused

Updated at December 2023

When you want to check if a document / website is focused, to act accordingly, you can use the following snippet for vanilla javascript:

0
1
2
3
4
5
6
7
8
9
10
 var isFocused = document.hasFocus();

const onFocus = () => {
    isFocused = true
};
const onBlur = () => {
    isFocused = false
}

window.addEventListener('focus', onFocus);
window.addEventListener('blur', onBlur);

If you want to use this in a react component you can use the following snippet:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
const [isFocused, setIsFocused] = useState(true);

useEffect(() => {
    const onFocus = () => setIsFocused(true);
    const onBlur = () => setIsFocused(false);

    window.addEventListener('focus', onFocus);
    window.addEventListener('blur', onBlur);

    return () => {
        window.removeEventListener('focus', onFocus);
        window.removeEventListener('blur', onBlur);
    };
}, []);

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.