-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
54 lines (41 loc) · 1.26 KB
/
index.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
51
52
53
class ChangeTitleOnLeave {
constructor(options) {
this.resolveAttrs(options);
this.listenVisibility();
}
resolveAttrs(options = {}) {
this.title = document.title;
this.options = {};
if (! options.title || options.title === '') {
throw Error('The `title` is required and must be a non-empty string.');
}
this.options.title = options.title;
this.options.timeout = typeof options.timeout === 'number' ? options.timeout : 0;
this.options.onHidden = typeof options.onHidden === 'function' ? options.onHidden : null;
this.options.onVisible = typeof options.onVisible === 'function' ? options.onVisible : null;
}
listenVisibility() {
window.addEventListener('visibilitychange', () => this.handleVisibility());
}
handleVisibility() {
const {timeout} = this.options;
setTimeout(() => this.updateTitle(), timeout * 1000);
}
updateTitle() {
const state = document.visibilityState;
const {title, onHidden, onVisible} = this.options;
if (state === 'hidden') {
document.title = title;
this.useCallback(onHidden);
}
if (state === 'visible') {
document.title = this.title;
this.useCallback(onVisible);
}
}
useCallback(callable) {
if (typeof callable !== 'function') return;
callable();
}
}
module.exports = ChangeTitleOnLeave;