I am setting my website to receive firebase notifications. I can receive it when in the background. But could not when in the foreground. I have followed this tutorial link to set up. https://medium.com/@a.adendrata/push-notifications-with-angular-6-firebase-cloud-massaging-dbfb5fbc0eeb.
I have initialize it in app.module.ts.
I have tried others similar stackoverflow solutions. But none of them is working so far.
I have tried to use AngularFireMessaging, and FirebaseApp. But both of them could not receive notification after sent.
import { FirebaseApp } from '@angular/fire';
import '@firebase/messaging';
import { AngularFireMessaging } from '@angular/fire/messaging';
setUpMessage() {
this.messaging = this.firebaseApp.messaging();
}
setUpFCM() {
this.afMessaging.messaging.subscribe(_messaging => {
_messaging.onMessage = _messaging.onMessage.bind(_messaging);
_messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
});
}
requestPermission() {
this.afMessaging.requestToken.subscribe(token => {
console.log(token);
}, error => {
console.error(error);
});
}
listenToNotifications() {
return this.afMessaging.messages;
}
listenNotifications() {
return this.messaging;
}
In my component.ts file, I initialized them and got the token from firebase. but cannot receive notification in the foreground.
ngOnInit() {
this.fcmTokenService.setUpMessage();
this.fcmTokenService.setUpFCM();
this.fcmTokenService.requestPermission();
this.validation_messages = this.printFormService.printValidationMessage();
this.listenNotification();
this.listenNotification2();
}
private listenNotification() {
this.fcmTokenService.listenToNotifications().subscribe(msg => {
// msg.content = JSON.parse(msg.data.content);
console.log(msg);
});
}
private listenNotification2() {
this.fcmTokenService.listenNotifications().onMessage(msg => {
console.log(msg);
});
}
I expect to receive the notification and console log it, but no result after many hours or retrying with different approaches.
On your firebase-messaging-sw.js or your service worker file?
importScripts('https://www.gstatic.com/firebasejs/7.6.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.6.0/firebase-messaging.js');
should have the same version with your firebase on package.json
"dependencies": {
...
"firebase": "^7.6.0",
...
}
More details here: https://github.com/angular/angularfire/issues/1904#issuecomment-543506629
I found that importScripts version in service Worker & version of library in package.json has to be same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With