Search code examples
angularweb-pushangular15

Angular and Navigator.setAppBadge


While building a PWA using Angular 15, and Service Workers, I've hit upon what may be a snag. I'm trying to set the badge count on the app, but conventional (non-Angular) use navigator.setAppBadge(x), which isn't available in Angular.

My solution has been to call "outside" of Angular, using a Script block in my index file, and then calling that by declaring it in my component, and finally using it during the observable of Angular. But it feels a bit like a hack. I'm wondering if there's a better solution? It works as-is, and I'm not hating it, per se, it's not like I'm modifying the Angular state or anything "from the outside".

The PWA will need to run on the usual range of modern browsers and devices, which is why I'm looking for something a bit more standards-compliant, unless of course this is the way to go.

I've tried googling whether Angular's Navigator supports setAppBadge, but couldn't find anything on this. Maybe my Google-Fu is weak. I even capitulated and asked chatGPT, but that was predictably useless.


Solution

  • You can do this:

    this.swPush.messages.subscribe(
        messages => {
            const badgeCount = (messages as any).notification?.data?.badgeCount;
            if( badgeCount ) {
                (navigator as any).setAppBadge( badgeCount );
            }
        }
    )
    

    However, this will only update the count when the app is open.