Check if the browser tab is in focus in ReactJS

后端 未结 6 789
暗喜
暗喜 2021-02-07 04:20

I have a website in ReactJS. I want to get a callback whenever my tab comes in focus or is hidden. I came across the Page Visibility API for this but I\'m not able to figure out

6条回答
  •  后悔当初
    2021-02-07 04:56

    None of these worked well for what I needed, which was a way to detect if a user switched between tabs, or minimized the browser by double clicking icon in the taskbar.

    They either fired off multiple times but did manage registered the correct state, didn't work when minimizing from the taskbar icon or just didn't manage to keep up with multiple actions one after another.

    Seeing as I needed to make a server request each time the focus changed, the above situations were a bit 'no'.

    So this is what I did:

    const DetectChatFocus = () => {
        const [chatFocus, setChatFocus] = useState(true);
    
        useEffect(() => {
            const handleActivityFalse = () => {
                setChatFocus(false);
                serverRequest(false);
            };
    
            const handleActivityTrue = () => {
                setChatFocus(true);
                serverRequest(true);
            };
    
            window.addEventListener('focus', handleActivityTrue);
            window.addEventListener('blur', handleActivityFalse);
    
            return () => {
                window.removeEventListener('focus', handleActivityTrue);
                window.removeEventListener('blur', handleActivityFalse);
            };
        }, [chatFocus]);
    };
    
    export default DetectChatFocus;
    

    Currently this seems to work very well, tested on both Chrome and Firefox, all you need to do is initialize it in a main component or wherever you need and it will keep track of the window focus for all those scenarios and it will only make one server request per action.

提交回复
热议问题