This is the first time I am working with serviceworkers and notifications.
I am trying to show a notification at a specified time. I tried doing it in the service worker as follows:
function showNotification() {
    setTimeout(function () {
        self.registration.showNotification('Title', {
            body: 'body blablabla',
            badge: 'assets/images/logo.jpeg',
            icon: 'assets/images/logo.jpeg',
            renotify: false,
            requireInteraction: true,
            silent: false,
            vibrate: [200, 100, 200],
            dir: 'ltr',
            lang: 'en-US'
        });
    }, 3000);
}
I don't get any notifications if I try this. When I delete the setTimeout function, I do get a notification so I assume it has something to do with the timeout. Is there another way or am I missing something?
Thanks!
Calling the function in my Chrome JavaScript function (outside of the Service Worker) actually works in my case, I tried it this way :
function showNotification() {
  navigator.serviceWorker.getRegistration().then(registration => {
    setTimeout(() => {
        registration.showNotification('Title', {
            body: 'body blablabla',
            badge: '/images/icon-light.png',
            icon: '/images/icon-light.png',
            renotify: false,
            requireInteraction: true,
            silent: false,
            vibrate: [200, 100, 200],
            dir: 'ltr',
            lang: 'en-US'
        });
    }, 3000);
  });
}
Calling showNotification from the SW works too, I just tried the following code along with the Applications -> Service Workers -> Push in the Chrome Devtools console button to send a Push notification and then display it after 3 seconds :
self.addEventListener('push', function(event) {
  if (event.data) {
    console.log('This push event has data: ', event.data.text());
  } else {
    console.log('This push event has no data.');
  }
  setTimeout(() => {
    self.registration.showNotification(
      'Title',
      {
        body: 'body blablabla',
        badge: '/images/icon-light.png',
        icon: '/images/icon-light.png',
        renotify: false,
        requireInteraction: true,
        silent: false,
        vibrate: [200, 100, 200],
        dir: 'ltr',
        lang: 'en-US'
      }
    ); 
  }, 3000);    
});
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With