close-box Documentation

pwaRegister(): Service worker registration

The pwaRegister() function will allow the registration of the service worker, namely to create or update it.

Function parameter

This function takes the service worker url as a parameter (relative or absolute)


pwaRegister(file)

Default value

By default the value of file is 'serviceworker.js'

The function

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}`)
}

Function call

Here is the function call used on pwabunga.js calling the file serviceworker.js present at the root of the PWA


pwaRegister()

Full function


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}`)
        }
    }
}

The functions of PWA Bunga!

Service worker registration

Improved user experience

Permissions