Check if the browser tab is in focus in ReactJS

后端 未结 6 790
暗喜
暗喜 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 05:16

    A more complete and optimized hook:

    import React, { useState, useEffect } from 'react'
    import _ from 'lodash'
    
    export default function useIsWindowFocused(): boolean {
        const [windowIsActive, setWindowIsActive] = useState(true)
    
        const handleActivity = React.useCallback(
            _.debounce(
                (e: { type: string }) => {
                    if (e?.type == 'focus') {
                        return setWindowIsActive(true)
                    }
                    if (e?.type == 'blur') {
                        return setWindowIsActive(false)
                    }
                    if (e?.type == 'visibilitychange') {
                        if (document.hidden) {
                            return setWindowIsActive(false)
                        } else {
                            return setWindowIsActive(true)
                        }
                    }
                },
                100,
                { leading: false },
            ),
            [],
        )
    
        useEffect(() => {
            document.addEventListener('visibilitychange', handleActivity)
            document.addEventListener('blur', handleActivity)
            window.addEventListener('blur', handleActivity)
            window.addEventListener('focus', handleActivity)
            document.addEventListener('focus', handleActivity)
    
            return () => {
                window.removeEventListener('blur', handleActivity)
                document.removeEventListener('blur', handleActivity)
                window.removeEventListener('focus', handleActivity)
                document.removeEventListener('focus', handleActivity)
                document.removeEventListener('visibilitychange', handleActivity)
            }
        }, [])
    
        return windowIsActive
    }

提交回复
热议问题