-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuse-page-visibility.ts
46 lines (40 loc) · 1.41 KB
/
use-page-visibility.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { useEffect, useState } from 'react';
interface IDocumentMultiBrowser {
hidden?: boolean;
msHidden?: boolean;
webkitHidden?: boolean;
}
const getUserAgentVisibilityProps = () => {
let hidden = 'hidden';
let visibilityChange = 'visibilitychange';
if (typeof (document as IDocumentMultiBrowser).hidden !== 'undefined') {
hidden = 'hidden';
visibilityChange = 'visibilitychange';
} else if (typeof (document as IDocumentMultiBrowser).msHidden !== 'undefined') {
hidden = 'msHidden';
visibilityChange = 'msvisibilitychange';
} else if (typeof (document as IDocumentMultiBrowser).webkitHidden !== 'undefined') {
hidden = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
return { visibilityChange, hidden };
};
export const usePageVisibility = () => {
const { visibilityChange, hidden } = getUserAgentVisibilityProps();
const [isVisible, setVisibility] = useState(true);
const handleVisibilityChange = () => {
// @ts-ignore
if (document[hidden]) {
setVisibility(false);
} else {
setVisibility(true);
}
};
useEffect(() => {
document.addEventListener(visibilityChange, handleVisibilityChange, false);
return () => {
document.removeEventListener(visibilityChange, handleVisibilityChange);
};
}, []);
return isVisible;
};