Skip to main content

Angular 9+ Firebase Cloud Messaging Push Notifications

 Are you looking for push notification which is normally you seen in ANDROID application or IOS application which is basically giving popup on your device notification tab when the application is closed user still received the notification. The same things can happen with your web application. In the case of the web application, you will receive the notification when the browser tab is not active and this is done by with the help of a service worker.

Now you might be wondering what is service worker ? or what is push notification ? as well so before i begin to explain it’s procedure it's better to understand some terminologies.

First, take look into what is Push Notifications

A push notification is a message popup similar to SMS. App publishers can send them at any time; users don’t have to be in the app or using their devices to receive them. They can do a lot of things; for example, they can show the latest sports scores, get a user to take any action, such as downloading a coupon or let a user know about an event, such as a flash sale.

Push notifications look like SMS text messages and mobile alerts, but they only reach users who have installed your app. Each mobile platform and browsers have support for push notifications. It gives applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent.

Second, look for prerequisites of Push Notifications

as we looking push notifications in angular 8 so you must have installed Node.js version > 10. NPM will be updated also because it will be used by default. Here, I am using Node version 10.16.3 and install the latest version of Angular CLI else you can upgrade your older version into the latest CLI by npm install -g @angular/cli@latest command.

once the project environment has been done you also require a firebase account to connect your web application into the cloud messaging.

1 ) simply visit into firebase.google.com

2 ) if you are new then click on sign up else you can log in into your old account

3) once login click into go to console tab which is in the top right corner

4) then click into Create a project

5) once the project has been created then look for its project settings General tab and create one app for getting its credentials

6 ) once your app is ready then simply copy its config for future use

Image for post

copy config

7) also copy the server key from the Cloud Messaging tab

Image for post

copy Legacy server key

Now your all prerequisites are complete 🙂

Now Create the Angular Project

Let’s create an Angular 8 project by using the following command:

ng new push-notification

cd push-notification

here we are using the firebase so we need to install that library so enter the following command in the same project directory.

npm install firebase @angular/fire --save

npm install firebase --save

npm audit fix (if any vulnerabilities found else ignore)

Now you have to create some file so follow the instruction carefully.

create manifest.json file save this file in the same folder where index.html file resides. We need to add a manifest.json file to our app and register it with the Angular CLI. Push Notifications use the service worker browser extension, which must be registered in this manifest.

{

  "gcm_sender_id": "YOUR-SENDER-ID"

}

then link it in the index.html file.

<head>

     <link rel="manifest" href="./manifest.json">

</head>

2. create firebase-messaging-sw.js Push messaging requires a service worker. This allows your app to detect new messages, even after the app has been closed by the user. and create this file in the same directory of manifest.json file which is in src/ directory.

Note:- Before importing the below script you need to check the latest version it's better if you import the latest version of the CDN link, so here i importing 7.6.0 version links.

importScripts('https://www.gstatic.com/firebasejs/7.6.0/firebase-app.js');

importScripts('https://www.gstatic.com/firebasejs/7.6.0/firebase-messaging.js');

firebase.initializeApp({

 apiKey: “from firebase config”,

 authDomain: “from firebase config”,

 databaseURL: “from firebase config”,

 projectId: “from firebase config”,

 storageBucket: “from firebase config”,

 messagingSenderId: “from firebase config”,

 appId: “from firebase config”,

 measurementId: “from firebase config”

});

const messaging = firebase.messaging();

3. we need to register these files in angular-cli.json

"assets": [

    "src/favicon.ico",

    "src/assets",

    "src/firebase-messaging-sw.js", // add this one

    "src/manifest.json" // this one also 

]

4. Now you have to create the service provider in my case I'm going to create a messaging service provider in the service folder which is an app directory. so move into the app directory and enter bellow command by cmd.

mkdir service

cd service

ng g s messaging

once service has been created you have to paste below exact code into messaging.service.ts file

import { Injectable } from '@angular/core';

import { AngularFireMessaging } from '@angular/fire/messaging';

import { BehaviorSubject } from 'rxjs'

@Injectable()

export class MessagingService {

currentMessage = new BehaviorSubject(null);

constructor(private angularFireMessaging: AngularFireMessaging) {

this.angularFireMessaging.messaging.subscribe(

(_messaging) => {

_messaging.onMessage = _messaging.onMessage.bind(_messaging);

_messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);

}

)

}

requestPermission() {

this.angularFireMessaging.requestToken.subscribe(

(token) => {

console.log(token);

},

(err) => {

console.error('Unable to get permission to notify.', err);

}

);

}

receiveMessage() {

this.angularFireMessaging.messages.subscribe(

(payload) => {

console.log("new message received. ", payload);

this.currentMessage.next(payload);

})

}

}

let’s understand its functions

requestPermission() : Browser/ device will ask to user for permission to receive notification. After permission is granted by the user, firebase will return a token that can use as a reference to send a notification to the browser.

receiveMessage() : This function will be triggered when a new message has received.

6. Update the Environment files

export const environment = {

production: false,

firebase: {

  apiKey: “from firebase config”,

  authDomain: “from firebase config”,

  databaseURL: “from firebase config”,

  projectId: “from firebase config”,

  storageBucket: “from firebase config”,

  messagingSenderId: “from firebase config”,

  appId: “from firebase config”,

  measurementId: “from firebase config”

}

};

7. Update the Components files

first we will update the App Module File

import { BrowserModule } from ‘@angular/platform-browser’;

import { NgModule } from ‘@angular/core’;

import { AppRoutingModule } from ‘./app-routing.module’;

import { AppComponent } from ‘./app.component’;

import { AngularFireMessagingModule } from ‘@angular/fire/messaging’;

import { AngularFireDatabaseModule } from ‘@angular/fire/database’;

import { AngularFireAuthModule } from ‘@angular/fire/auth’;

import { AngularFireModule } from ‘@angular/fire’;

import { MessagingService } from ‘./service/messaging.service’;

import { environment } from ‘../environments/environment’;

import { AsyncPipe } from ‘../../node_modules/@angular/common’;

@NgModule({

   declarations: [AppComponent],

   imports: [

      AppRoutingModule,

      BrowserModule,

      AngularFireDatabaseModule,

      AngularFireAuthModule,

      AngularFireMessagingModule,

      AngularFireModule.initializeApp(environment.firebase),

   ],

   providers: [MessagingService,AsyncPipe],

   bootstrap: [AppComponent]

})

export class AppModule { }

then in the HTML part, we can use pipe async and JSON

{{ message | async | json }}

And now update the App Components file

import { Component } from ‘@angular/core’;

import { MessagingService } from ‘./service/messaging.service’;

@Component({

  selector: ‘app-root’,

  templateUrl: ‘./app.component.html’,

  styleUrls: [‘./app.component.css’]

})

export class AppComponent {

  title = ‘push-notification’;

  message;

  constructor(private messagingService: MessagingService) { }

ngOnInit() {

  this.messagingService.requestPermission()

  this.messagingService.receiveMessage()

  this.message = this.messagingService.currentMessage

 }

}

Finally, we did the Setup process... 😉

Now run the project

run application using ng serve -o after compilation is complete, open can your browser and browser will ask for permission.

Image for post

ask for notification

once you click on the allow button than it will print the token id on browser console sometime it will take time to load the token id but surely you will get that id in console dialog.

Image for post

here you can see the TOKEN ID which is generated after the permission

now we are ready to go…

Now look for sending a push notification

You can also hit Firebase Cloud Messaging directly using cURL.

curl -X POST \

  https://fcm.googleapis.com/fcm/send \

  -H 'Authorization: key=YOUR-SERVER-KEY' \

  -H 'Content-Type: application/json' \

  -d '{ 

 "notification": {

  "title": "Hey there", 

  "body": "Subscribe to mighty ghost hack youtube channel"

 },

 "to" : "YOUR-GENERATED-TOKEN"

}'

Also, you can use the postman for sending the request i will demonstrate you by the postman

copy below JSON request and enter into the body part and also provide authorization key in the header section of postman before sending any request over googleapis and authorization key is nothing but the legacy serve key which we saw in prerequisite sections.

{

 "notification": {

 "title": "Hey there", 

 "body": "Subscribe to might ghost hack youtube channel"

 },

 "to" : "YOUR-GENERATED-TOKEN"

}

Image for post

include your legacy server key in the header section

once all done we can send the request to the server https://fcm.googleapis.com/fcm/send

once i click on the send button on postman i will receive the popup and one thing important you have to note down when your project is in active tab means open in browser or you are in the same tab then message will appear on HTML but it will not give you any popup until and unless you minimize it or move into another tab. when you move into another tab or minimize the browser than service worker doing his work to show you the popup message

now let me show the popup when the project tab is not in an active mode

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...