The pwaRegister()
function will allow the registration of the service worker, namely to create or update it.
This function takes the service worker url as a parameter (relative or absolute)
pwaRegister(file)
By default the value of file
is 'serviceworker.js'
We test if the browser supports service workers
if ("serviceWorker" in navigator) {
...
}
We are trying to register the service worker
try {
const registration = await navigator.serviceWorker.register(file);
...
}
If the service worker registration is successful, its status is returned to the console
if (registration.installing) {
console.log("Service worker installing")
} else if (registration.waiting) {
console.log("Service worker installed")
} else if (registration.active) {
console.log("Service worker active")
}
Otherwise, the error is returned to the console
catch (error) {
console.error(`Registration failed with ${error}`)
}
Here is the function call used on pwabunga.js calling the file serviceworker.js
present at the root of the PWA
pwaRegister()
const pwaRegister = async (file = 'serviceworker.js') => {
if ("serviceWorker" in navigator) {
try {
const registration = await navigator.serviceWorker.register(file);
if (registration.installing) {
console.log("Service worker installing")
} else if (registration.waiting) {
console.log("Service worker installed")
} else if (registration.active) {
console.log("Service worker active")
}
}
catch (error) {
console.error(`Registration failed with ${error}`)
}
}
}
pwaInstall()
: Promotion and PWA install buttonpwaUpdate()
: Application updatepwaShare()
: Using device native sharingpwaParams()
: PWA parameters insert