-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathclient.ts
More file actions
60 lines (49 loc) · 1.47 KB
/
client.ts
File metadata and controls
60 lines (49 loc) · 1.47 KB
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
54
55
56
57
58
59
60
type ReportFunction = (ev: timer.stat.Event) => Promise<void>
const INTERVAL = 1000
/**
* Tracker client, used in the content-script
*/
export default class TrackerClient {
docVisible: boolean = false
start: number = Date.now()
report: ReportFunction
constructor(report: ReportFunction) {
this.report = report
}
init() {
this.docVisible = document?.visibilityState === 'visible'
document?.addEventListener('visibilitychange', () => this.changeState(document?.visibilityState === 'visible'))
setInterval(() => this.collect(), INTERVAL)
}
private changeState(docVisible: boolean) {
this.docVisible && !docVisible && this.pause()
!this.docVisible && docVisible && this.resume()
this.docVisible = docVisible
}
private async collect(ignoreTabCheck?: boolean) {
if (!this.docVisible) return
const now = Date.now()
const lastTime = this.start
this.start = now
const interval = now - lastTime
if (interval <= 0 || interval > INTERVAL * 2) {
// Invalid time
return
}
const data: timer.stat.Event = {
start: lastTime,
end: now,
url: location?.href,
ignoreTabCheck
}
try {
await this.report?.(data)
} catch (_) { }
}
private pause() {
this.collect(true)
}
private resume() {
this.start = Date.now()
}
}