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
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}
}