-
Notifications
You must be signed in to change notification settings - Fork 5
/
lib.js
50 lines (41 loc) · 1.47 KB
/
lib.js
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
47
48
49
50
import React, { useEffect, useRef } from 'react';
export default function usePageVisibility(cb, delay) {
const timeoutId = useRef(null);
const browserCompatApi = () => {
let hidden, visibilityChange;
if ('hidden' in document) {
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if ('mozHidden' in document) { // Firefox up to v17
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
} else if ('webkitHidden' in document) { // Chrome up to v32, Android up to v4.4, Blackberry up to v10
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
return {
hidden,
visibilityChange
}
}
const cleanupTimeout = () => clearTimeout(timeoutId.current);
useEffect(() => {
const { hidden, visibilityChange } = browserCompatApi();
if (typeof cb !== 'function') throw new Error('callback must be a function')
const handleVisibilityChange = () => {
if (delay) {
if (typeof delay !== 'number' || delay < 0) {
throw new Error('delay must be a positive integer');
}
if (timeoutId.current) cleanupTimeout();
timeoutId.current = setTimeout(() => cb(!document[hidden]), delay);
} else {
cb(!document[hidden]);
}
};
document.addEventListener(visibilityChange, handleVisibilityChange);
return () => {
document.removeEventListener(visibilityChange, handleVisibilityChange);
};
}, [cb]);
}