diff --git a/docs/modules/workbox.md b/docs/modules/workbox.md index 60c0cf31..c8d8f98c 100644 --- a/docs/modules/workbox.md +++ b/docs/modules/workbox.md @@ -18,6 +18,12 @@ 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`). + +See [workbox-window](https://developers.google.com/web/tools/workbox/modules/workbox-window) docs for more information about use cases. + ## Options diff --git a/packages/workbox/package.json b/packages/workbox/package.json index 3d1c0c9f..feaa40dc 100644 --- a/packages/workbox/package.json +++ b/packages/workbox/package.json @@ -8,6 +8,7 @@ "access": "public" }, "dependencies": { - "@nuxtjs/pwa-utils": "3.0.0-beta.10" + "@nuxtjs/pwa-utils": "3.0.0-beta.10", + "workbox-window": "4.0.0" } } diff --git a/packages/workbox/templates/sw.register.js b/packages/workbox/templates/sw.register.js index b9b2fd6c..d01c650b 100755 --- a/packages/workbox/templates/sw.register.js +++ b/packages/workbox/templates/sw.register.js @@ -1,9 +1,17 @@ -if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('<%= options.swURL %>', { +import { Workbox } from 'workbox-window/build/workbox-window.<%= options.dev ? 'dev' : 'prod' %>.mjs' + +export default async function(ctx, inject) { + const workbox = new Workbox('<%= options.swURL %>', { scope: '<%= options.swScope %>' - }).then(function(registration) { - window.$sw = registration - }).catch(function(error) { - console.error('Service worker registration failed:', error) }) + + // Inject as $workbox + inject('workbox', workbox) + + if (!'serviceWorker' in navigator) { + workbox._unsupported = true + return // Unsupported browser! + } + + workbox.register() } diff --git a/yarn.lock b/yarn.lock index eaabed41..6d3854c6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11271,6 +11271,18 @@ wordwrap@~1.0.0: resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" integrity sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus= +workbox-core@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/workbox-core/-/workbox-core-4.0.0.tgz#3b4aa11c9d739361ed8916b7611abc3b6fefed8b" + integrity sha512-FRoOUuJBl7COTwvGO5FC9k0VyYGv/LkjVqgVwKk9MXQn/Xi+bvGDcqSVF7qfT+sJ6Ffcr/V+dVMpoZAE/X5e+g== + +workbox-window@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/workbox-window/-/workbox-window-4.0.0.tgz#a4d6404c96cc65d4882f79331d4e812c10f912a6" + integrity sha512-gdLzP/L0vu5Gi3pdUYtVNmg0yE7OriEuYZBoLt8AYoILXh6cta9WsWHKQ0/pXfmEmZywr4Dfu0qkLLvc9VlZGQ== + dependencies: + workbox-core "^4.0.0" + worker-farm@^1.5.2: version "1.6.0" resolved "https://registry.yarnpkg.com/worker-farm/-/worker-farm-1.6.0.tgz#aecc405976fab5a95526180846f0dba288f3a4a0"