2023-02-09 17:27:49 +03:00
|
|
|
import { useEffect, useRef } from 'preact/hooks';
|
2023-02-07 19:31:46 +03:00
|
|
|
|
|
|
|
export default function usePageVisibility(fn = () => {}, deps = []) {
|
2023-02-09 17:27:49 +03:00
|
|
|
const savedCallback = useRef(fn, deps);
|
|
|
|
|
2023-02-07 19:31:46 +03:00
|
|
|
useEffect(() => {
|
|
|
|
const handleVisibilityChange = () => {
|
|
|
|
const hidden = document.hidden || document.visibilityState === 'hidden';
|
2023-02-09 17:27:49 +03:00
|
|
|
console.log('👀 Page visibility changed', hidden ? 'hidden' : 'visible');
|
|
|
|
savedCallback.current(!hidden);
|
2023-02-07 19:31:46 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
document.addEventListener('visibilitychange', handleVisibilityChange);
|
|
|
|
return () =>
|
|
|
|
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
2023-02-09 17:27:49 +03:00
|
|
|
}, []);
|
2023-02-07 19:31:46 +03:00
|
|
|
}
|