-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathworker.js
More file actions
80 lines (68 loc) · 1.72 KB
/
worker.js
File metadata and controls
80 lines (68 loc) · 1.72 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import client from './client'
import environment from './environment'
import router from './router'
import state from './state'
const worker = { ...state.worker }
delete state.worker
const emptyQueue = Object.freeze([])
const queuesProxyHandler = {
set(target, name, value) {
target[name] = value
client.update()
return true
},
get(target, name) {
return target[name] || emptyQueue
},
}
worker.queues = new Proxy({}, queuesProxyHandler)
const workerProxyHandler = {
set(target, name, value) {
if (target[name] !== value) {
target[name] = value
client.update()
}
return true
},
}
const proxy = new Proxy(worker, workerProxyHandler)
async function register() {
if (!environment.production) return
const request = `/service-worker.js`
try {
proxy.registration = await navigator.serviceWorker.register(request, { scope: '/' })
} catch (error) {
console.error(error)
}
}
async function unregister() {
if (!environment.development) return
const registrations = await navigator.serviceWorker.getRegistrations()
for (let registration of registrations) {
window.location.reload()
console.log("SW FOUND", { registration })
registration.unregister();
}
}
if (worker.enabled) {
if ('serviceWorker' in navigator) {
window.addEventListener('beforeinstallprompt', async function (event) {
event.preventDefault()
proxy.installation = event
unregister()
})
register()
}
}
window.addEventListener('online', () => {
proxy.online = true
if (environment.mode === 'ssg') {
router._update(router.url)
} else {
proxy.responsive = true
}
})
window.addEventListener('offline', () => {
proxy.online = false
})
export default proxy