ServiceWorker doesn't run the first time

Viewed 51

I have a project where I use a serviceWorker to send notifications.
I would like when the user authorizes notifications the serviceWorker is activated and the user's notification subscription is sent to the backend.
For some reason when I check if the serviceWorker state is active, in the console an object appears but for the code it is as if it were null.
Could someone help me?

Notification.requestPermission().then(async function(permission) {
        if(permission === "granted"){
            if("serviceWorker" in navigator){
                const sw = await navigator.serviceWorker.register("scripts/worker.js", {
                    scope: "/billings/scripts/"
                });
                console.log(sw); // is an object (View Image)
                if(sw.active){ // The code stop HERE because sw.active is null
                    const subscription = await reg.pushManager.subscribe({
                        userVisibleOnly: true,
                        applicationServerKey: urlBase64ToUint8Array(pubKey)
                    });
                    fetch("http://192.168.1.10:8080/pushSub", {
                        method: "POST",
                        headers: {
                            'Accept': 'application/json',
                            'Access-Control-Allow-Origin': '*',
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + localStorage.getItem("user")
                        },
                        body: JSON.stringify({
                            sub: JSON.stringify(subscription)
                        })
                    });
                }
            }
        }else{
            alert("Permissão não autorizada.");
        }
    });

Service Worker:

self.addEventListener("push", e => {
    const data = e.data.json();
    self.registration.showNotification(data.title, {
      body: data.message,
      icon: "http://image.ibb.co/frYOFd/tmlogo.png"
    });
});

Google chrome log: Google chrome log


Response Try:

function createSW(){
    if("serviceWorker" in navigator){
        navigator.serviceWorker.register("scripts/worker.js", {
            scope: "/billings/scripts/"
        }).then(async function(reg){
            console.log(reg);
            if(reg.active){
                const subscription = await reg.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: urlBase64ToUint8Array(pubKey)
                });
                fetch("http://192.168.1.10:8080/pushSub", {
                    method: "POST",
                    headers: {
                        'Accept': 'application/json',
                        'Access-Control-Allow-Origin': '*',
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + localStorage.getItem("user")
                    },
                    body: JSON.stringify({
                        sub: JSON.stringify(subscription)
                    })
                });
            }
        });
    }
}
1 Answers

The register function runs asynchronous, so the service-worker is not yet ready when you test for if(sw.active) Have a close look at your log, there you see that the service-worker is still installing.{installing:ServiceWorker,...}

Your code should look like:

navigator.serviceWorker.register("scripts/worker.js", {
  scope: "/billings/scripts/"
}).then(function(registration) {
  //next code goes here
}

By using then(...) you wait for the registration to be completed.

Related