diff options
Diffstat (limited to 'library/sw-controller.js')
-rw-r--r-- | library/sw-controller.js | 67 |
1 files changed, 48 insertions, 19 deletions
diff --git a/library/sw-controller.js b/library/sw-controller.js index d5065a933..23d67026e 100644 --- a/library/sw-controller.js +++ b/library/sw-controller.js @@ -1,34 +1,63 @@ const EventEmitter = require('events') -module.exports = class serviceWorkerController extends EventEmitter{ +module.exports = class ClientSideServiceWorker extends EventEmitter{ constructor (opts) { super() this.fileName = opts.fileName - this.registerOpts = opts.registerOpts - this.serviceWorker = navigator.serviceWorker - } + this.startDelay = opts.startDelay + this.serviceWorkerApi = navigator.serviceWorker + this.serviceWorkerApi.onmessage = (event) => this.emit('message', event) + this.serviceWorkerApi.onerror = (event) => this.emit('error') - 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) + // temporary function + this.askForId = (message) => { + this.sendMessage('check-in') + .then((data) => console.log(`${message}----${data}`)) } + + // if (!!this.serviceWorkerApi) this.askForId('before') + + if (opts.initStart) this.startWorker() + + this.on('ready', (sw) => { + this.askForId('ready') + }) } - registerWorker () { - return this.serviceWorker.register(this.fileName, this.registerOpts) - .then(sw => { - return sw + get controller () { + return this.sw || this.serviceWorkerApi.controller + } + + + startWorker () { + return this.registerWorker() + .then((sw) => { + this.sw = sw + this.askForId('after register:') + this.sw.onerror = (err) => this.emit('error', err) + this.sw = sw + this.emit('ready', this.sw) }) + .catch((err) => this.emit('error', err)) } - syncSW (registeredSW) { - return registeredSW.sync.register('sync') - .then(() => { - console.log('sync') + registerWorker () { + return this.serviceWorkerApi.register(this.fileName) + .then((registerdWorker) => { + return new Promise((resolve, reject) => { + this.askForId('after') + let timeOutId = setTimeout(() => { + if (this.serviceWorkerApi.controller) return resolve(this.serviceWorkerApi.controller) + if (registerdWorker.active) return resolve(registerdWorker.active) + return reject(new Error('ClientSideServiceWorker: No controller found and onupdatefound timed out')) + }, this.startDelay || 1000 ) + + registerdWorker.onupdatefound = (event) => { + this.emit('updatefound') + registerdWorker.update() + } + }) }) } @@ -43,7 +72,7 @@ module.exports = class serviceWorkerController extends EventEmitter{ resolve(event.data.data) } } - self.serviceWorker.controller.postMessage(message, [messageChannel.port2]) + this.controller.postMessage(message, [messageChannel.port2]) }) } } |