diff options
Diffstat (limited to 'library/sw-controller.js')
-rw-r--r-- | library/sw-controller.js | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/library/sw-controller.js b/library/sw-controller.js new file mode 100644 index 000000000..d5065a933 --- /dev/null +++ b/library/sw-controller.js @@ -0,0 +1,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]) + }) + } +} |