ng new push-notification
cd push-notification
npm install firebase @angular/fire --save
npm i @firebase/messaging
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"
}
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();
<!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>
"assets": [
"src/favicon.ico",
"src/assets",
"src/manifest.json",
"src/firebase-messaging-sw.js"
],
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",
}
};
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
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.
Messaging => New Compaigns => Notifications => Type title and message in textbox and hit the send test message button.
No comments:
Post a Comment