diff --git a/docs/modules/workbox.md b/docs/modules/workbox.md index e21bd693..e7ba4e3e 100644 --- a/docs/modules/workbox.md +++ b/docs/modules/workbox.md @@ -20,9 +20,18 @@ workbox: { ## Workbox Window -A global `$workbox` service is injected to the application, which can be used either by plugins (via `context.app.$workbox`) or pages (via `this.$workbox`). +This module uses [workbox-window](https://developers.google.com/web/tools/workbox/modules/workbox-window) to register and communicate with workbox service worker. +See docs for more information about use cases. -See [workbox-window](https://developers.google.com/web/tools/workbox/modules/workbox-window) docs for more information about use cases. +As service worker is registered in background, to access instance you have to await on a promise: + +```js +const workbox = await window.$workbox + +if (workbox) { + // Service worker is available +} +``` ## Options diff --git a/packages/workbox/templates/sw.register.js b/packages/workbox/templates/sw.register.js index 4494136b..a332177d 100755 --- a/packages/workbox/templates/sw.register.js +++ b/packages/workbox/templates/sw.register.js @@ -1,27 +1,18 @@ -function onError(error) {<% if (options.dev) { %>console.error('Error registering workbox:', error) <% } %>} - -export default function (ctx, inject) { - let workbox = {} +async function register() { + if (!'serviceWorker' in navigator) { + throw new Error('serviceWorker is not supported in current browser!') + } - try { - // workbox-window does not detects unsupported browsers - if (!'serviceWorker' in navigator) { - throw new Error('serviceWorker is not supported in current browser!') - } + const { Workbox } = await import('workbox-cdn/workbox/workbox-window.<%= options.dev ? 'dev' : 'prod' %>.es5.mjs') - // Use require() instead of import() to prevent creating extra chunk - // Use es5 version to prevent crashing older browsers while parsing bundle - const { Workbox } = require('workbox-cdn/workbox/workbox-window.<%= options.dev ? 'dev' : 'prod' %>.es5.mjs') + const workbox = new Workbox('<%= options.swURL %>', { + scope: '<%= options.swScope %>' + }) - workbox = new Workbox('<%= options.swURL %>', { - scope: '<%= options.swScope %>' - }) + await workbox.register() - workbox.register().catch(onError) - } catch (error) { - onError(error) - } - - // Inject as $workbox - inject('workbox', workbox) + return workbox } + +window.$workbox = register() + .catch(error => {<% if (options.dev) { %> console.error('Error registering workbox:', error) <% } %>})