PWA Push Notification via Angular - Guidelines | MPS

Blog

Multi-Programming SolutionsBlog For ClientsPWA Push Notification Guidelines

PWA Push Notification Guidelines

 

Push-notifications have recently become one of the essential attributes of mobile applications. Thus, according to a study by Accengage, 7.8% of mobile users respond to these kinds of messages, which means an impressive potential increase to the existing conversion rates of your software. Generally speaking, push technology is beneficial in that it gives the user targeted information that may be useful to them individually.

Partly for this reason, push-notifications have become an integral attribute of the concept of Progressive Web Applications (PWA) – a project of Google, which was first introduced to the public in 2015 and is gradually becoming one of the mainstream formats in web development. But let’s dive a bit deeper into the related definitions, discuss push-notifications in the context of promoting info via PWA, and take a look at a clear example of how to integrate a specific PWA notification (Android version).

Push Notifications in PWA – How Do They Work?

Let’s start by figuring out how a Progressive Web Apps push notification works as a whole. 

In fact, it is an ordinary message sent based on certain parameters from the server to the user device (smartphone, tablet, and even PC if we enable PWA capacities). Meanwhile, a PWA solution shouldn’t be necessarily launched for these notifications to pop up. All that is needed is that a user stays online.

What do push notifications from a PWA look like commonly? Upon receiving a push notification, the user device can react differently: in case the screen is locked, an abbreviated notification is displayed on the lock screen, similar to a regular SMS; if the device is in sleep mode, the user will see a notification after it is activated. 

Push notifications are largely identical to email messages (because they are also based on web concepts) and SMS (their appearance is very similar), however, unlike the first ones, they are sent directly to the device, and, unlike the latter, they are a much more cost-effective (the cost of SMS mailing is quite high). In addition, push messages can contain rich content: pictures, gifs, links, and even a button-shaped badge (up to two of them, to be exact).

Push notifications are triggered by Service Workers, which are automatically activated the first time a user opens PWA. You can start regularly sending automated push notifications only upon an initial user’s consent. After that, they will be receiving them even with a closed browser, since it is the OS that acts as an intermediary for displaying the message here. By the way, this approach allows you to save both the smartphone battery and traffic.

If the application is deleted by the user, service workers will inform your PWA server about which devices should no longer receive notifications. 

Messages are transmitted in the JSON format. Despite this, developers usually do not have to delve into the “jungles” of JavaScript to integrate push notifications with PWA – as a rule, they use a special graphical Push API, which even a layman can handle.

What Browsers & Platforms Support PWA Push Notifications?

And now a few words about platform and browser support. PWA push notifications are supported by many popular mobile platforms – Android, Firebase OS, Windows, and BlackBerry, as well as Chrome, Safari, Firefox, and Opera browsers. Such an impressive list suggests that you will not have any difficulty providing support for your PWA with popular platforms and web browsers.

As for iOS PWA push notification, specialists at Apple still aren’t sure how to most properly introduce them with their exclusive devices, even in 2020.

Push Notification PWA Best Practices

Since push notifications are a platform-independent and cost-effective tool for promoting your services, they are often recommended to be used by marketers to lead users through the sales funnel. For this reason, push notifications are very common in eCommerce solutions based on Magento, WordPress, Shopify, and other frameworks.

In particular, this type of messages is recommended to be used to notify your target audience of some urgent events: coupons, discounts or promotions that are valid for a limited time period. Also, their distribution is appropriate when fresh content appears. And finally, you can use them to optimize a sales funnel journey for individual customers (for example, notifications about products waiting in the cart).

Important!!! Before connecting the PWA push notification API, it is very important to remember that this is one of the most intrusive ways to attract the attention of your target audience – notifications immediately pop up on the homescreen over the rest of the messages. Moreover, in some situations, they do not allow you to continue using the device until you read them. 

Thus, it is extremely important to make sure that your PWA background notification is useful and doesn’t cause irritation. Therefore – remember: too frequent use of push notifications can lead to a negative result and force your target audience to refrain from using your services.

So how often should you send such messages? The optimal frequency for push notifications is 2 messages per week. However, this indicator may vary depending on the specifics of your target audience.

How to Integrate Push Notifications with PWA

Let’s see how to integrate a feature as handy as push notification with PWA via Angular. The following is the part of the Angular-based app’s structure with a detailed addition of the required code. 

Let’s start!

Register a service worker in the main.js file:


import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
      
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
      
if (environment.production) {
      
    enableProdMode();
      
}
      
platformBrowserDynamic().bootstrapModule(AppModule).then(() => {
      
    if ('serviceWorker' in navigator && environment.production) {
      
        navigator.serviceWorker.register('/ngsw-worker.js');
      
    }
      
}, err => console.error(err));
    

Check the current status of subscription and subscribe users to push notifications:


import {Component, OnInit} from '@angular/core';
import {MatDialog} from '@angular/material/dialog';
import {UserService} from '../../../core/services/user.service';
import {SwPush} from '@angular/service-worker';
import {CommonDialogComponent} from '../../../shared/components/dialog/common-dialog.component';
import {vapidPubKey} from '../../../core/config';
import {first} from 'rxjs/operators';
 
@Component({
templateUrl: './push-notifications.component.html',
styleUrls: ['./push-notifications.component.scss']
})
export class PushNotificationsComponent implements OnInit {
constructor(public swPush: SwPush,
          public userService: UserService,
          private dialog: MatDialog,
    ) {  }
 
    ngOnInit() {
this.checkSubscription();
    }
 
    checkSubscription() {
if (('PushManager' in window) && this.swPush.isEnabled) {
this.swPush.subscription.pipe(first()).subscribe(pushSubscription => {
if (pushSubscription) {
              // saving subscription credentials in DB on server
this.userService.savePushSubscription(pushSubscription);
                }
            });
        }
    }
 
    subscribe() {
this.swPush.requestSubscription({serverPublicKey: vapidPubKey})
        .then(sub => {
            // saving subscription credentials in DB on server
this.userService.savePushSubscription(sub);
        })
        .catch(err => {
this.showNotificationsDisabledOrNotSupportedDialog();
        });
    }
 
private showNotificationsDisabledOrNotSupportedDialog() {
this.userService.currentUser.pushSubscribed = false;
this.dialog.open(CommonDialogComponent, {
data: {
msg: `Either you have blocked this site from sending notifications in browser settings ` +
`or your browser doesn't support this functionality.`
            }
        });
    }
}

Patch the Angular’s ngsw-worker.js file to open the application on notification click:


// Handle the fetch, message, and push events.
this. scope.addEventListener( 'fetch', (event) => this.onFetch(event));
this.scope.addEventListener( 'message', (event) =>  this.onMessage(event));
this.scope.addEventListener('push', (event) => this.onPush(event));
this.scope.addEventListener('notificationclick', (event) => {
    event.notification.close();
if(event.notification.data.url) {
        event.waitUntil(clients.matchAll({
type: "window"       
         }).then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == event.notification.data.url && 'focus' in client){
return client.focus();
           }
       }
if (clients.openWindow) {
return clients.openWindow(event.notification.data.url);
       }
   }));
}
});

Voila! This brief set of commands helps to integrate push-notifications with a PWA solution of your own.

Summary

Push notifications play a crucial role in promoting content and are an integral component of PWA. They are usually used to send out information that expires very quickly.

The maximum efficiency of PWA mobile push notifications can be achieved by combining them on a single platform with other communication channels, such as email and SMS. Only such an integrated approach to interacting with a client will make this process seamless and efficient.

If you want to create your own PWA and connect PWA mobile notifications to it, contact us and we will offer you a cost-effective, reliable, and scalable implementation of your idea.

Please rate this article

5 stars