Navigation

Tuesday 4 January 2022

Angular : Web Push Notifications with Firebase Cloud Messaging and Angular

Step 1: Create a new angular project "WebPushNotification" by the following code.


ng new push-notification
cd push-notification


Step 2: We need to install these libraries.


npm install firebase @angular/fire --save
npm i @firebase/messaging


Step 3: We need to create some files for our project.
Add the manifest.json and firebase-messaging-sw.js file inside the src folder and copy-paste the below code.

 manifest.json

{
    "gcm_sender_id": "549348xxxxx1"
}

firebase-messaging-sw.js

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


firebase.initializeApp({
    apiKey: "AIzaSyCMxpExxxJKtZMxxxFjyXJGs8F8FCm-mA",
    databaseURL: 'https://webpushnotify-1xxx5f.firebaseio.com',  
    appId: '1:549348xxx4551:web:1a07a9cc7226b6f0b14982',  
    authDomain: "webpushnotify-1xxxf.firebaseapp.com",
    projectId: "webpushnotify-1xxxf",
    storageBucket: "webpushnotify-1xxxf.appspot.com",
    messagingSenderId: "5493xxx44xx1",
    measurementId: "G-N3HxxxFYN9"
  });
 
  // Retrieve an instance of Firebase Messaging so that it can handle background
  // messages.
  const messaging = firebase.messaging();

Step 4: After creating the manifest.json and  firebase-messaging-sw.js file, add the link into the index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>WebPushNotification</title>
  <base href="/">
  <link rel="manifest" href="./manifest.json"/>
  <link rel="firebaseApp" href="./firebase-messaging-sw.js"/>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Step 5: We need to add these files inside the angular.json

  "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/manifest.json",              
              "src/firebase-messaging-sw.js"                      
            ],

Step 6:  Add the below parameter to your environment.ts file, you can find these parameters in your firebase account as shown in the screenshot.

export const environment = {
  production: false,
   firebase: {
    apiKey: "AIzaSyCMxpEFlOJKtZMxxxEFjyxxxGs8F8FCm-mA",
    databaseURL: 'https://webpushnotify-1xxxf.firebaseio.com',  
    appId: '1:549348944551:web:1a07a9cc7226b6f0b14982',  
    authDomain: "webpushnotify-1xxxf.firebaseapp.com",
    projectId: "webpushnotify-1xxxf",
    storageBucket: "webpushnotify-1xxxf.appspot.com",
    messagingSenderId: "549348944551",
  }
};





Step 7: Import files as shown below in app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AngularFireModule } from '@angular/fire/compat';
import { AngularFireMessagingModule } from '@angular/fire/compat/messaging';
import { environment } from 'src/environments/environment';
import { AngularFireDatabaseModule } from '@angular/fire/compat/database';
import { AngularFireAuthModule } from '@angular/fire/compat/auth';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    AngularFireMessagingModule,
    AngularFireModule.initializeApp(environment.firebase),  
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }



Step 8: Create service (messaging.service.ts) in the service folder and copy-paste the below code. 

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { AngularFireMessaging} from '@angular/fire/compat/messaging';
import { getMessaging, getToken } from "firebase/messaging";
@Injectable({
  providedIn: 'root'
})
export class MessagingService { currentMessage = new BehaviorSubject(null);
  currentToken :any;
  constructor(private afMessaging: AngularFireMessaging) {

  }
  requestPermission() {
    this.afMessaging.requestPermission
      .subscribe(
        token => {
          debugger;
          console.log('Permission granted! Save to the server!', token);
        },
        error => {
          debugger;
          console.error(error);
        },
      );
    debugger;
  }
  getToken() {
    const messaging = getMessaging();
    getToken(messaging, { vapidKey: 'BPnoeaxxxmm_mwsIfxxxxyW-5-xxx-5PtxxSy8_K-XFCcxxx' })
      .then((currentToken) => {
        if (currentToken) {
          debugger;
          //Send the token to your server or save to your local storage for view.
// this token will be used to send notification through firebase register app.
// that will be shown in screenshot.
          console.log('Registration token available. '+currentToken);        
          this.currentToken = currentToken;
        } else {
          debugger;
          // Show permission request UI
          console.log('No registration token available. Request permission to generate one.');
       
        }
      }).catch((err) => {
        debugger;
        console.log('An error occurred while retrieving token. ', err);
     
      });  
  }
}



Key pair you can use as vapidKey


Step 9: By registering service work we can get the browser token that will be used for sending notifications, so copy-paste the below code as shown in  app.component.ts

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 = 'WebPushNotification';
  currentToken: any;
  constructor(private _messageService: MessagingService) {
    debugger;
    navigator.serviceWorker.register('./firebase-messaging-sw.js')
      .then(function (registration) {
        debugger;
        console.log('Registration successful, scope is:', registration.scope);
      }).catch(function (err) {
        debugger;
        console.log('Service worker registration failed, error:', err);
      });
    this.requestPermission();
  }

  requestPermission() {
    this._messageService.requestPermission();
  }
  getToken() {
    debugger;
    this.currentToken = this._messageService.getToken();
    debugger;
  }  
}

Copy the token that you will get. You can display this token to your page by saving it in your local storage.




Step 10: These firebase account screenshots are shown, how to send notifications to your web browser.

Messaging => New Compaigns => Notifications => Type title and message in textbox and hit the send test message button.
 

Paste copied token that you receive from your application and press plus (+) sign button to add the token as shown.



After adding a token you can test by pressing the button "Test".


Finally, you can receive a notification as shown below screenshot. If still, you are not getting the notification please check your Manage Notification and allow notification to chrome browser.


Open manage notification and switch on the notification of chrome as shown below screenshot.






No comments:

Post a Comment