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