Created
August 12, 2019 06:08
-
-
Save archangel-irk/0193267178b25b306d064986c134f444 to your computer and use it in GitHub Desktop.
React Hook - Page Visibility API (tab document visible)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from 'react'; | |
// Spec | |
// https://www.w3.org/TR/page-visibility-2/ | |
// MDN | |
// https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API | |
// https://developers.google.com/web/updates/2017/03/background_tabs | |
enum VisibilityState { | |
HIDDEN = 'hidden', | |
VISIBLE = 'visible', | |
} | |
const EVENT_NAME = 'visibilitychange'; | |
export function isPageVisible(): boolean { | |
// Server-side rendering case | |
if (typeof document === 'undefined') return true; | |
return document.visibilityState === VisibilityState.VISIBLE; | |
} | |
function usePageVisibility(): boolean { | |
const [pageVisible, setPageVisible] = useState<boolean>(isPageVisible()); | |
function handleVisibilityChange(event: Event): void { | |
setPageVisible(isPageVisible()); | |
} | |
useEffect(function subscribeVisibilityChange(): () => void { | |
document.addEventListener(EVENT_NAME, handleVisibilityChange); | |
return function unsubscribeVisibilityChange(): void { | |
document.removeEventListener(EVENT_NAME, handleVisibilityChange); | |
}; | |
}, []); | |
return pageVisible; | |
} | |
export { usePageVisibility }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment