Check if the browser tab is in focus in ReactJS

后端 未结 6 793
暗喜
暗喜 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:01

    There is no reliable method to check it, so you need to combine few methods together. Here is Context for react-hooks

    import React, { useState, useEffect } from 'react'
    
    export const WindowContext = React.createContext(null)
    
    export const WindowContextProvider = props => {
      const [windowIsActive, setWindowIsActive] = useState(true)
    
    
      function handleActivity(forcedFlag) {
        if (typeof forcedFlag === 'boolean') {
          return forcedFlag ? setWindowIsActive(true) : setWindowIsActive(false)
        }
    
        return document.hidden ? setWindowIsActive(false) : setWindowIsActive(true)
      }
    
      useEffect(() => {
        const handleActivityFalse = () => handleActivity(false)
        const handleActivityTrue = () => handleActivity(true)
    
        document.addEventListener('visibilitychange', handleActivity)
        document.addEventListener('blur', handleActivityFalse)
        window.addEventListener('blur', handleActivityFalse)
        window.addEventListener('focus', handleActivityTrue )
        document.addEventListener('focus', handleActivityTrue)
    
        return () => {
          window.removeEventListener('blur', handleActivity)
          document.removeEventListener('blur', handleActivityFalse)
          window.removeEventListener('focus', handleActivityFalse)
          document.removeEventListener('focus', handleActivityTrue )
          document.removeEventListener('visibilitychange', handleActivityTrue )
        }
      }, [])
    
      return {props.children}
    }
    

提交回复
热议问题