- Check if service worker is supported
- Register a service worker
- Check if a service worker exists in a given URL
- I want the service worker to control higher pages
- Listen for install event in service worker
- Listen for activate event in service worker
Check if service worker is supported
main.js
1 | if ('serviceWorker' in navigator) { |
Register a service worker
main.js
1 | navigator.serviceWorker.register('sw.js') |
Check if a service worker exists in a given URL
If you want to do this in code, you can only do it within the same origin as the worker(s) you want to check for. Within the same origin, you can use getRegistration(url)
(which gives you a promise that will resolve to undefined
or a ServiceWorkerRegistration
object for the URL), or getRegistrations()
(which gives you a promise for an array of ServiceWorkerRegistration
objects). E.g.:
main.js
1 | navigator.serviceWorker.getRegistrations().then(registrations => { |
How to use navigator.serviceWorker.ready property?
I want the service worker to control higher pages
- Change the
scope
option when registering the service worker
main.js
1 | navigator.serviceWorker.register('/app/service-worker.js', { |
- Set the Service-Worker-Allowed HTTP header in your server config for the request serving the service worker script.
nginx config
1 | location ~* (service-worker\.js)$ { |
Apache config
1 | LoadModule rewrite_module modules/mod_rewrite.so |
Listen for install event in service worker
service-worker.js
1 | // Listen for install event, set callback |
Listen for activate event in service worker
service-worker.js
1 | self.addEventListener('activate', function(event) { |