blob: d5065a933e225dc50a13aa00a0ea08c8c513e2f4 (
plain) (
blame)
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
|
const EventEmitter = require('events')
module.exports = class serviceWorkerController extends EventEmitter{
constructor (opts) {
super()
this.fileName = opts.fileName
this.registerOpts = opts.registerOpts
this.serviceWorker = navigator.serviceWorker
}
startWorker () {
// check to see if their is a preregistered service worker
if (!this.serviceWorker.controller) {
return Promise.resolve(this.registerWorker())
} else {
return Promise.resolve(this.serviceWorker.ready)
}
}
registerWorker () {
return this.serviceWorker.register(this.fileName, this.registerOpts)
.then(sw => {
return sw
})
}
syncSW (registeredSW) {
return registeredSW.sync.register('sync')
.then(() => {
console.log('sync')
})
}
sendMessage (message) {
const self = this
return new Promise((resolve, reject) => {
var messageChannel = new MessageChannel()
messageChannel.port1.onmessage = (event) => {
if (event.data.err) {
reject(event.data.error)
} else {
resolve(event.data.data)
}
}
self.serviceWorker.controller.postMessage(message, [messageChannel.port2])
})
}
}
|