Do Not Show This Notification Again Angular 2

In this post, we are going to go through a complete example of how to implement Web Push Notifications in an Angular Application using the Athwart Service Worker.

Note that these are the exact aforementioned native notifications that we receive for example on our mobile phones home screen or desktop, but they are triggered via a spider web application instead of a native app.

These notifications tin fifty-fifty be displayed to the user if all application tabs are closed, thank you to Service Workers! When well used, Push notifications are a bully manner of having our users re-appoint with our application.

This is a step-by-step tutorial, so I invite y'all to lawmaking along every bit we implement Push Notifications in an existing application.

We volition also larn forth the way how Push Notifications work in general, as we follow and explicate the consummate menses that a given notification follows.

The Angular PWA serial

Note that this mail service is part of the Angular PWA Serial, here is the complete series:

  • Service Workers - Practical Guided Introduction (several examples)
  • Angular App Shell - Boosting Awarding Startup Performance
  • Angular Service Worker - Step-By-Step Guide for turning your Awarding into a PWA
  • Angular Push button Notifications - Footstep-by-Step Guide

Table of Contents

In this post, nosotros will cover the following topics:

  • How do Push Notifications work?
  • Browser Push button Service Providers
  • What is a VAPID fundamental pair?
  • generating a VAPID fundamental pair using node webpush
  • Subscribing to Push Notifications
  • showing once again the Allow/Deny Notifications popup
  • Understanding the PushSubscription object and its properties
  • How to employ the Push button Subscription?
  • Sending Push Notifications from a Node backend
  • Push Notifications In Action - Demo
  • Source Code + Github Running Example (complete Angular PWA)

So without further ado, allow's get started learning how to handle Button Notifications with the Angular Service Worker.

Introduction to Push button Notifications

What we know every bit Spider web Push button Notifications are actually based on 2 separate browser standards:

  • Push API - this is an API that allows messages to exist pushed from a server to a browser (even when the site isn't focused or the browser is airtight)

  • Notifications API: displays native arrangement notifications to the user

The Push button API is what allows the bulletin to exist pushed from a server to the browser, and the Notifications API is what allows the message to exist displayed, once it gets to the browser.

But discover that we can't push notifications from our server straight to the user's browser. Instead, only certain servers that browser evolution companies (like Google, Mozilla, etc.) specifically choose will be able to push button notifications to a given browser.

These servers are known as a Browser Button Service. Annotation that for example, the Push Service used past Chrome is dissimilar than the one used by Firefox, and each Push Service is nether command of the corresponding browser company.

Browser Button Service Providers

As we sometimes run into online, Push Notifications can exist very confusing to the user, and browser implementers want to ensure that browser users have a proficient online experience at all times.

This means that browser providers want to be able to block out certain notifications from existence displayed to the user, for instance if the notifications are too frequent.

The fashion that browsers like Chrome or Firefox ensure that Push messages don't cause user experience issues is to funnel all push button messages over servers nether their control.

For example, in the example of the Chrome browser, all Button messages come to the browser via the Firebase Deject Messaging service and Not directly from our application server.

Firebase Cloud Messaging acts in this case as the Chrome Browser Push button Service. The Push Service that each browser uses cannot exist changed, and is adamant by the browser provider.

In society to be able to evangelize a message to a given user and simply to that user, the Push Service identifies the user in an bearding fashion, ensuring the user privacy. Also, the Push Service does not know the content of the messages, as they are encrypted.

Let's then go through the whole lifecycle of a particular message, to understand in item how everything works. Nosotros will first by uniquely identifying our server, and acquire why that's important.

Why place our server as a Push source?

The first thing that we should practise is to uniquely identify our server to the several Browser Push Services available.

Each Push Service will analyze the behavioral patterns of the letters being sent in order to avoid disruptive experiences, so identifying our server and using the push messages correctly over fourth dimension will increment our odds that the Push button Service will deliver our messages in a timely way.

We will then start by uniquely identifying our Application server using a VAPID key pair.

What is a VAPID key pair?

VAPID stands for Voluntary Application Server Identification for Web Push protocol. A VAPID key pair is a cryptographic public/private cardinal pair that is used in the post-obit way:

  • the public fundamental is used every bit a unique server identifier for subscribing the user to notifications sent by that server
  • the private key needs to be kept underground (dissimilar the public cardinal) and its used by the awarding server to sign messages, before sending them to the Push button Service for delivery

Generating a VAPID fundamental pair using node web-button

Let's beginning by generating a VAPID key using the node webpush library. We volition kickoff install the webpush library globally, as a command line tool:

          npm install web-button -g                  

Nosotros tin can and then generate a VAPID primal pair with the post-obit command:

                      web-push generate-vapid-keys --json                  

Using this command, here is what a VAPID key pair looks like:

We can now use the VAPID Public Fundamental to subscribe to Button Notifications using the Angular Service Worker.

Subscribing to Push Notifications

The first thing that nosotros will demand is the Angular Service Worker, and for that here is a guide for how to add together information technology to an existing Athwart application.

Once we have the Angular Service Worker installed, we can now request the user permission for sending Push button Notifications:

Allow'southward pause down what is going on in this code sample:

  • the user clicks on the Subscribe button and the subscribeToNotifications() method gets executed

  • using the swPush service, nosotros are going to ask the user if he allows our server (identified by the VAPID public key) to send him Spider web Push messages

  • the requestSubscription() method returns a Hope which emits the push subscription object, in example the user allows notifications

  • The user is and so going to come across a browser popup asking him to allow or deny the request:

Push Notifications Popup

  • if the user accepts the request, the Promise returned past requestSubscription() is going to be evaluated successfully, and a push subscription object is going to be passed to .and so()

While testing this on localhost, you might accidentally hit the wrong button in the popup. The next time that you click subscribe, the popup will not exist displayed.

Instead, the Promise is going to be rejected and the catch block in our lawmaking sample above is going to be triggered.

Here is what we need to do in guild to take the popup displayed once more:

  • go to chrome://settings/content/notifications
  • gyre downwardly the Block listing, containing all the websites that are blocked from emitting button notifications
  • delete localhost from the Block list
  • Click the Subscribe push once more

The popup should now appear once again, and if we click on the Permit choice, a Push button Subscription object will be generated.

The PushSubscription object

Here is what the push button subscription object looks like, as we receive it in the and then() clause:

Let's now break down the content of the subscription object, as that will help us to empathise better how Push Notifications work in general:

  • endpoint: This contains a unique URL to a Firebase Cloud Messaging endpoint. This url is a public just unguessable endpoint to the Browser Push Service used past the application server to send push button notifications to this subscription
  • expirationTime: some messages are time sensitive and don't need to be sent if a certain time interval has passed. This is useful in certain cases, for example, if a message might contain an authentication code that expires subsequently 1 minute
  • p256dh: this is an encryption key that our server will use to encrypt the message, before sending it to the Button Service
  • auth: this is an authentication secret, which is 1 of the inputs of the bulletin content encryption procedure

All the information present in the subscription object is necessary to be able to transport push notifications to this user.

How to apply the Push Subscription object?

In one case we get a push subscription, we demand to store it somewhere where nosotros can use information technology afterwards, in one case we determine to send a message to this user.

In our example, nosotros are sending the whole subscription object to the backend via an HTTP request done by the NewsletterService, and the consummate subscription object will be stored in the database for later use.

Sending Push Notifications from a Node Backend

Now that we accept the multiple subscription objects stored in the database, we can now use them to send button letters using the webpush library.

Let's and so create a REST endpoint using Express, that when triggered volition result in a notification to be sent to all subscribers.

In this example, nosotros are sending a Notification informing that a newsletter is now available:

Allow's now break down this instance. Nosotros are using over again the webpush module, only this time to encrypt, sign and send a button notification to all subscribers:

  • we start by initializing the webpush module, by passing it the VAPID key pair

  • in this simple example the keys are in the code, which is Not recommended. Instead, we tin pass a reference to a JSON file containing the key pair via a command line argument

  • we are and then initializing an Express application, and we take created an HTTP POST endpoint for the /api/newsletter url

In gild to trigger this endpoint, our awarding can send an HTTP postal service call to /api/newsletter.

Notice that this endpoint would take to be protected by both authentication and authorization middleware, in order to ensure that but an ambassador can trigger the sending of a newsletter.

Building the Push Message body

In gild for the Angular Service Worker to correctly display the message, nosotros need to use the format shown in the code.

Namely, we will the payload to be 1 root object containing one property named notification, otherwise the letters will not be displayed to the user.

Also the text and epitome of the notification, we tin can too specify a mobile vibration pattern via the vibrate property.

Sending the Push Notification using webpush

Once nosotros take the bulletin payload ready, we tin can ship it to a given subscriber via a call to webpush.sendNotification():

  • the first argument is the push subscription object, only like we received information technology in the browser after the user has clicked the Allow Notifications option

  • the second argument is the notification payload itself, in JSON format

The webpush library volition then do the following steps:

  • the payload of the message is going to exist encrypted using the p256dh public cardinal and the auth hallmark undercover

  • the encrypted payload is and so going to be signed using the VAPID individual central

  • the message is so going to be sent to the Firebase Deject Messaging enpoint specified in the endpoint property of the subscription object

What happens at the level of the Push button Service?

When the Push service receives the message (in this case Firebase Cloud Messaging), it will know to which browser instance to forward the message to based on the unique url of the endpoint.

Annotation that the Push Service does not know the content of the message because its encrypted, so information technology cannot inspect it to decide if the message should go through or non.

But the Push button Service might decide to cake the message, if for instance this subscriber has already been receiving besides many messages.

In most cases, what will happen is that the Push Service is going to forward the message payload to the user's browser.

Push button Notification Demo

Once the Button Service pushes the message to the user browser, the bulletin is then going to be decrypted and passed to the Angular Service Worker.

The Angular Service Worker volition then apply the browser Notifications API to display a Notification to the user.

The end issue is a arrangement notification similar to the one that nosotros often receive from mobile apps:

Push Notification Demo

Source Lawmaking + Github Running Example (complete PWA)

A running example of the complete code is bachelor hither on this branch on Github. The PWA features demonstrated are:

  • Application Download & Installation
  • Application Version Direction
  • Ane-Click Install with App Manifest
  • Awarding Data Caching
  • Awarding Trounce
  • Push button Notifications
  • sample Express Server using webpush

I hope that this post helps with getting started with sending Push Notifications and that you enjoyed it!

If y'all would like to learn a lot more Athwart Progressive Web Applications, we recommend checking the Athwart PWA Course, where we cover PWAs in much more than detail.

If you have some questions or comments delight let me know in the comments below and I volition become dorsum to you.

To go notified of upcoming posts on Progressive Web Applications and other Angular topics, I invite you to subscribe to our newsletter:

If you are just getting started learning Angular, have a look at the Angular for Beginners Course:

reinhartbesse1954.blogspot.com

Source: https://blog.angular-university.io/angular-push-notifications/

Belum ada Komentar untuk "Do Not Show This Notification Again Angular 2"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel