Search code examples
javascriptjqueryasync-awaitweb-push

Uncaught TypeError : self.showLocalNotificationWrap is not a function


So I am trying to send a notification using web push and it just does not work. I see the event gets received but no notification shows up.

Here is the code for the 'push' event in my service worker:

self.addEventListener('push', async (event) => {
    console.log("Push received data - ", event.data.text());
    const pushData = await event.data.text();
    let data, title, body;
    try{
      data = await JSON.parse(pushData);
      title = data.title;
      body = data.body;
    }catch(e){
      title = "untitled";
      body = pushData;
    }
    
    const options = {
      title : title,
      body : body, 
      icon : '/favicon.ico',
    }

    self.showLocalNotificationSW(title, body, self.registration);

})

And the showLocalNotificationSw the push event calls:

const showLocalNotificationSW = async (title, body, swRegistration) => {
    swRegistration.showNotification(title, options);
}

I see in the console it says self.showNotificationWrap is not a function in the console. What does it mean?

I don't have any function named showNotificationWrap.

the error:

sw.js:48 Uncaught TypeError: self.showLocalNotificationWrap is not a function
    at sw.js:48

How do I fix this?

How do I fix this?


Solution

  • Turns out I only needed to unregister and register the service worker again to fix the problem.

    Here's the modified push event code:

    self.addEventListener('push', async function received(event) {
      let data, title, body;  
      data = event.data.text();
      console.log("Push received event - " + data);
    
        try{
          data = JSON.parse(data);
          console.log(JSON.stringify(data));
          title = data.title;
          body = data.body;
        }catch(error){
          console.error(error);
          title = "Undefined";
          body = data;
        }
    
        event.waitUntil(showNotificationSW(title, body, self.registration));
    
    })