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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...