-
Notifications
You must be signed in to change notification settings - Fork 10
/
request-monitor.js
70 lines (58 loc) · 1.62 KB
/
request-monitor.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
self.addEventListener('message', function handler(event) {
if (event.data === 'NETWORK_IDLE_ENQUIRY') {
event.ports[0].postMessage(
self.requestMonitor.isIdle ?
'NETWORK_IDLE_ENQUIRY_RESULT_IDLE' :
'NETWORK_IDLE_ENQUIRY_RESULT_NOT_IDLE',
);
}
});
if (self.requestMonitor) {
throw new Error('ServiceWorker already has a method named `requestMonitor`. Rename the method for network idle callback to work.')
} else {
self.requestMonitor = {
requestSet: {},
isIdle: true,
idleTimeoutId: null,
minIdleTime: 200,
listen({ clientId, request }) {
clearTimeout(this.idleTimeoutId)
this.isIdle = false
if (!clientId)
return
if (this.requestSet[clientId]) {
this.requestSet[clientId].add(request)
} else {
this.requestSet[clientId] = new Set([request])
}
},
setIdleAfterTimeout(fn) {
if (this.idleTimeoutId) {
clearTimeout(this.idleTimeoutId)
}
this.idleTimeoutId = setTimeout(() => {
if (fn) fn()
this.isIdle = true
}, this.minIdleTime)
},
unlisten({ clientId, request }) {
if (!clientId) {
this.setIdleAfterTimeout()
return
}
this.requestSet[clientId].delete(request)
if (!clientId) {
return
}
if (this.requestSet[clientId].size === 0) {
this.setIdleAfterTimeout(() => {
const matchedClient = self.clients.get(clientId)
matchedClient.then((client) => {
if (!client) return
client.postMessage('NETWORK_IDLE_CALLBACK')
})
})
}
},
}
}