androidiosangularpush-notificationweb-push

How to display Notfications on Android/iOS using @angular/service-worker


I already prepared my Angular App to receive web push messages by subscribing to SwPush.messages

When a message is received, I can trigger browser desktop notifications with the Notification API.

On Android and iOS (16.4 RC) the messages are received, but no push notification is displayed.

As I understood, I have to use ServiceWorkerRegistration.showNotification() because the Notification API is not supported on mobile devices.

(Browser support: showNotification vs Notification)

Is there a way to access the service worker registration of the angular service worker package? (Or any other method to send a native notification on mobile devices)


Solution

  • I was able to access the ServiceWorkerRegistration by using navigator:

        this.swPush.messages.subscribe({
          next: (message) => {
            const title = message.Notification.Title;
            const notification = new Notification(title);
            navigator.serviceWorker.getRegistration().then((reg) => {
              if (reg != null) {
                reg.showNotification(title);
              }
            });
          },
          error: (err) => {
            this.messages.push(err);
          },
        });