Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not receiving FCM messages #1904

Closed
BradyShober opened this issue Sep 30, 2018 · 48 comments
Closed

Not receiving FCM messages #1904

BradyShober opened this issue Sep 30, 2018 · 48 comments

Comments

@BradyShober
Copy link

BradyShober commented Sep 30, 2018

I have tried following the documentation in order to set up browser notifications for the application my team is currently developing. While I am able to obtain an FCM registration token, when I try to send a notification it does not appear to be received by the application. We are using the default firebase-messaging-sw.js

Version info

Ionic 3.9.2
Angular 5.2.10
Firebase ^5.5.1
AngularFire ^5.0.2

Browsers tested: Chrome 69.0.3497.100, Firefox 63.0b10

How to reproduce these conditions

Create a new Ionic project and install required packages.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { FcmProvider } from '../providers/fcm/fcm';
import { NotificationProvider } from '../providers/fcm/notifications';

import * as firebase from 'firebase';

import { AngularFireModule } from '@angular/fire';

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


const config = {
  //Firebase configuration information
}; 

firebase.initializeApp(config);

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    AngularFireModule.initializeApp(config),
    AngularFireMessagingModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    FcmProvider,
    NotificationProvider
  ]
})
export class AppModule {}

fcm.ts provider

import { Injectable } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { Platform } from 'ionic-angular';
import { mergeMapTo } from 'rxjs/operators';
import { Observable } from 'rxjs-compat';


@Injectable()
export class FcmProvider {


  constructor(private platform: Platform, private afMessaging: AngularFireMessaging) {

  }

  requestPermission(){
    return this.afMessaging.requestPermission.pipe(mergeMapTo(this.afMessaging.tokenChanges));
  }

  listen(){
    console.log("listening for messages");
    return this.afMessaging.messages;
  }

}

notification.ts provider

import { Injectable } from '@angular/core';
import { FcmProvider } from './fcm';
import { Platform } from 'ionic-angular';
import { AlertController } from 'ionic-angular';

@Injectable()
export class NotificationProvider {

    constructor(private platform: Platform, private fcm: FcmProvider, private alertCtrl: AlertController){}

    initializeNotifications(){

        this.fcm.requestPermission()
            .subscribe(token =>{
              console.log(token);
              this.fcm.listen()
                .subscribe(message => {
                console.log(message);
                this.notificationOpen(message);
                });
            });

    }

    notificationOpen(data){
        console.log(JSON.stringify(data));
        var alert;

        alert = this.alertCtrl.create({
            title: 'Request Received',
            message: 'A request has been received, would you like to accept it?',
            buttons: [
                {
                    text: 'Decline',
                    role: 'cancel'
                },
                {
                    text: 'Accept',
                    handler: () => {
                        this.acceptRequest(); 
                    }
                }
            ]
        });
        alert.present();
    }

    acceptRequest(){
        //call provider to accept request
        console.log("Request Accepted");
    }
}

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { NotificationProvider } from '../../providers/fcm/notifications';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [
    NotificationProvider
  ]
})
export class HomePage {

  constructor(public navCtrl: NavController, private notifications: NotificationProvider) {
    notifications.initializeNotifications();

  }

}

Expected behavior

When a notification is sent we should be seeing a log entry in the console and the notification should open.

Actual behavior

There is no log message and no notification opens.

@kobvel
Copy link

kobvel commented Dec 18, 2018

@BradyShober any resolution here? I am facing the same issue

@thongnx6
Copy link

thongnx6 commented Dec 30, 2018

I have faced the same issue. After that, I tried this code, it works for me.

this.angularFireMessaging.messaging.subscribe((_messaging) => {
        _messaging.onMessage = _messaging.onMessage.bind(_messaging);
        _messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
})

then

/**
 * hook method when new notification received in the foreground
 */
receiveMessage() {
    this.angularFireMessaging.messages.subscribe((payload) => {
        console.log("new message received. ", payload);
        this.currentMessage.next(payload);
    })
}

@fmandres92
Copy link

I have the same issue please. How can help me ??

@Shifs
Copy link

Shifs commented Mar 29, 2019

I am having the same issue . If I try CURL from Postman , it gives success response but does not store in firebase. If I directly create JSON in firebase database , then also I am not getting PUSH notification

@BradyShober
Copy link
Author

We have since switched to react-native and are no longer using Angular, but shortly before we switched we realized that the issue we had been experiencing was due to using the firebase console to try to send notifications to web, which does not work, and found when we used the admin sdk we were able to get the notifications. Not sure if that is the same issue for others here having issues getting notifications.

@CodeByBryan
Copy link

CodeByBryan commented Apr 9, 2019

I have only been using the web client, but have found that the only way that the client will receive messages is if it includes the Notification object. When sending a message with only the Data object it shows it was sent successfully and gives me an ID on return, but the client never receives it. I am hoping to find a solution since I really don't need the Notification functionality. If someone has figured this out, let me know!

@alihalabyah
Copy link

Any updates here? Is this project still maintained?

@Thomas0921
Copy link

I need help too, I can receive the notification in the background, but the onMessage or messages.subscribe (for foreground) is not triggering when receiving notifications.

@lancelynyrd
Copy link

Any solution on this one? i have the save issue, it was working on background but for the foreground it doesnt really being triggered.
no error, no response. but background is working.
this.afMessaging.messages.subscribe((res) => {
console.log(firebase listenMessage::, res);
}, e => console.log(error listenMessage::, e));

@sgallard
Copy link

Same for me here, working on background but for the foreground doesn't trigger

@azhararmar
Copy link

Same here, the background works and foreground doesn't.

@lancelynyrd
Copy link

@azhararmar @sgallard i have fixed my problem by matching the version of importScript inside the firebase-messaging-sw.js and the version of firebase install in package.json

@azhararmar
Copy link

@lancelynyrd I fixed the issue by changing the version of importScript from 5.x to 7.x

@khetho
Copy link

khetho commented Nov 12, 2019

@lancelynyrd solution worked for me

@link4hy
Copy link

link4hy commented Nov 18, 2019

@azhararmar U save my ass.

@Dhamo-krish
Copy link

If still it doesn't work , Add the PublicVapidKey to _messaging which belong to FireMessaging promise of messaging.service

this.angularFireMessaging.messaging.subscribe((_messaging) => {
_messaging.usePublicVapidKey('');
})

To get key Project Settings->Cloud Messaging

@parth181195
Copy link

I guess firebase versions above 7.6.0 are not compatible with @angular/fire 5.3.0 I tried with 7.6.3 and 7.7.0 but I can't get it to work .but it works fine with 7.6.0

@AlMorton
Copy link

THIS! I've tried using anything above 7.5.0 but it wouldn't work.

@rtsdemo123
Copy link

I'm also having same issue (working great in background not working in foreground)
I tried several changes:

  1. Changing the libraries from 5.5 to 7.7 or to 7.6
  2. I tried also to add this code
    this.angularFireMessaging.messaging.subscribe((_messaging) => {
    _messaging.usePublicVapidKey('xxx');
    })
    xxx - is the key I placed from the web configuration under cloud messaging in the firebase project.
  3. I also tried to play with the json I'm sending to the server-worker, sent a few variations
    with data + notification payload, only data, only notification.
    strangely I'm receiving the push notification only if the notification payload is present in the json
    otherwise it's not showing anything (even in the background) not sure if it's related to this
    problem.

This is the code of my messaing.service.ts so far:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { mergeMapTo } from 'rxjs/operators';
import { take } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs'

@Injectable()
export class MessagingService {

  currentMessage = new BehaviorSubject(null);

  constructor(
    private angularFireDB: AngularFireDatabase,
    private angularFireAuth: AngularFireAuth,
    private angularFireMessaging: AngularFireMessaging) {
    this.angularFireMessaging.messaging.subscribe(
      (_messaging) => {
        _messaging.onMessage = _messaging.onMessage.bind(_messaging);
        _messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
      }
    )
  }

  /**
   * update token in firebase database
   *
   * @param userId userId as a key
   * @param token token as a value
   */
  updateToken(userId, token) {
    // we can change this function to request our backend service
    this.angularFireAuth.authState.pipe(take(1)).subscribe(
      () => {
        const data = {};
        data[userId] = token
        this.angularFireDB.object('fcmTokens/').update(data)
      })
  }

  /**
   * request permission for notification from firebase cloud messaging
   *
   * @param userId userId
   */
  requestPermission(userId) {
    this.angularFireMessaging.requestToken.subscribe(
      (token) => {
        console.log(token);
        this.updateToken(userId, token);
      },
      (err) => {
        console.error('Unable to get permission to notify.', err);
      }
    );
  }

  /**
   * hook method when new notification received in foreground
   */
  receiveMessage() {
    this.angularFireMessaging.messages.subscribe(
      (payload) => {
        console.log("new message received. ", payload);
        this.currentMessage.next(payload);
      })

      this.angularFireMessaging.messaging.subscribe((_messaging) => {
        _messaging.usePublicVapidKey('xxx');
      })
  }
}

@vincepunkrock
Copy link

I guess firebase versions above 7.6.0 are not compatible with @angular/fire 5.3.0 I tried with 7.6.3 and 7.7.0 but I can't get it to work .but it works fine with 7.6.0

It would be great if Angular Fire would tell exactly which version of firebase to use.

@vincepunkrock
Copy link

I indeed fixed it temporarily by using firebase 7.6.0 with angular/fire 5.4.0. 7.8.0 wouldn't work.

@rachitsakhidas
Copy link

There is workaround for it.

You need to modify your custom messaging service little bit.

Inside constructor you need to replace following code

this.angularFireMessaging.messaging.subscribe(
(_messaging: any) => {
_messaging.onMessage = _messaging.onMessage.bind(_messaging);
messaging._next = (payload: any) => {
console.log(payload);
};
_messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
}
);
with that

this.angularFireMessaging.messaging.subscribe(
(_messaging: any) => {
// _messaging.onMessage = _messaging.onMessage.bind(_messaging);
_messaging._next = (payload: any) => {
console.log(payload);
};
_messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
}
);
Then you will get push notification even you are in fore-ground.

Thanks & Regards Rachit V. Sakhidas

@rtsdemo123
Copy link

thanks @rachitsakhidas but it did not help. I use postman in order to test push notifications: this is how I push notifications in the test website that I'm currently testing...

I have two headers, one of which is the authorization which consists of "key=with the key from the firebase console" another field is Content-Type that is equal to application/json

The body (json) of the request is:

{

"collapse_key" : "type_a",
"notification" : {
"body" : "Body of Your Notification45545544545",
"title": "Title of Your Notification",
"action":"www.google.com"
},
"data" : {
"channel": "default",
"id": 123,
"title": "Test Notification with action",
"body": "Force touch to reply",
"sound": "default",
"priority": "high",
"click_action": "com.myapp.MyCategory",
"badge": 10,
"number": 10,
"ticker": "My Notification Ticker",
"auto_cancel": true,
"large_icon":
"https://image.freepik.com/free-icon/small-boy-cartoon_318-38077.jpg",
"icon": "ic_launcher",
"big_text": "Show when notification is expanded",
"sub_text": "This is a subText",
"color": "red",
"vibrate": 300,
"wake_screen": true,
"group": "group",
"picture":
"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png",
"ongoing": true,
"my_custom_data": "my_custom_field_value",
"lights": true,
"show_in_foreground": true
},
"to": "fSrmQgaSEd4kduQG-" a unique identifier from firebase.
}

thanks for your help!

@yanlyan
Copy link

yanlyan commented Feb 23, 2020

It happens again on firebase 7.9.1 and angularfire 6.0.0-rc.1

@ijurao
Copy link

ijurao commented Apr 5, 2020

any update here? same poblem again with firebase7.13.2

@entropia-studio
Copy link

Testing with firebase 7.14.1 doesn't work neither. I was able to get the foreground notifications following this article but is a workaround really.

Here is the final code related with the article but is necessary to install the Angular Service Worker (ngsw) also.

Hope the firebase team fix this sooner because get the foreground messages is really important for the package functionality.

@FrancescoPaiola
Copy link

FrancescoPaiola commented May 4, 2020

any update?

@pufanalexandru
Copy link

I'm having the same issue, with Firebase 7.14.2 and Angular Fire 6.0.0. Any solution?

@fenrirdrk
Copy link

Same issue with "firebase": "7.14.4" and "@angular/fire": "6.0.0". Any idea?

@ijurao
Copy link

ijurao commented May 18, 2020 via email

@karthik11788
Copy link

I have the same issue but its working fine on localhost but in https only working the background notification FIREBASE 7.6.0

@fenrirdrk
Copy link

fenrirdrk commented May 28, 2020

I finally got this done, Im sure there is a better and proper soluciotion but, based on @rachitsakhidas, and removing worker registration from index file and make it in angular.json it worked for me:

"firebase": "^7.14.5",
"@angular/fire": "^5.4.2",

I did tried others many versions of both and theirs convinations and nothing seem to worked, so i registerd a firebase-messaging-sw.js
and as workaround to catch the push event in foreground i used the messaging callback like this:

this.afMessaging.messaging.subscribe(
        (messaging: any) => {
          messaging.onMessageCallback = (payload: any) => {
            this.alertCtrl.create({
              header: payload.notification.title,
              message: payload.notification.body,
              buttons: ['Entendido'],
              cssClass: 'confirmation-alert',
              backdropDismiss: false
            }).then(alert => {
              alert.present().then();
              alert.onDidDismiss().then(async () => {
              // do something
              });
            });
          };
          messaging.onTokenRefresh = messaging.onTokenRefresh.bind(messaging);
        });

I'm working with ionic in this case but maybe, this can save some time to someone.

@NethajiV
Copy link

Still not working for me @fenrirdrk can you please let me know what you mean by "removing worker registration from index file and make it in angular.json". Also what version of ionic framework you are using

Now I'm going to try the version you have suggested.

@NethajiV
Copy link

As suggested in https://github.com/angular/angularfire/blob/master/docs/ionic/v3.md I have installed angularfire2 using the command

npm install angularfire2 firebase promise-polyfill --save

Now my version is
"@angular/fire": "^5.4.2",
"angularfire2": "^5.4.2",
"firebase": "^7.14.5",

It seems there is bug in firebase-messaging.js event handler so only we are not receiving the messages.

image

Now I have commented the onMessage and added a listener in service worker, now I'm getting foreground messages to web,

image

Hope this will save others time, as I have spent more than one day trying different approaches and trying different versions.

Note: still not receiving the background messages on web. If anyone knows the solution please let me know.

@karthik11788
Copy link

karthik11788 commented May 30, 2020 via email

@karthik11788
Copy link

karthik11788 commented May 30, 2020 via email

@jperezg86
Copy link

For me the @fenrirdrk solution worked great! Using the same versions and using the event listener:

messaging.onMessageCallback = (payload: any) => {
console.log(payload);
}

Thanks!

@Radecom
Copy link

Radecom commented Jun 11, 2020

I finally got this done, Im sure there is a better and proper soluciotion but, based on @rachitsakhidas, and removing worker registration from index file and make it in angular.json it worked for me:

"firebase": "^7.14.5", "@angular/fire": "^5.4.2",

I did tried others many versions of both and theirs convinations and nothing seem to worked, so i registerd a firebase-messaging-sw.js
and as workaround to catch the push event in foreground i used the messaging callback like this:

this.afMessaging.messaging.subscribe(
        (messaging: any) => {
          messaging.onMessageCallback = (payload: any) => {
            this.alertCtrl.create({
              header: payload.notification.title,
              message: payload.notification.body,
              buttons: ['Entendido'],
              cssClass: 'confirmation-alert',
              backdropDismiss: false
            }).then(alert => {
              alert.present().then();
              alert.onDidDismiss().then(async () => {
              // do something
              });
            });
          };
          messaging.onTokenRefresh = messaging.onTokenRefresh.bind(messaging);
        });

I'm working with ionic in this case but maybe, this can save some time to someone.

Work for me, Thanks!

@quocthanh2694
Copy link

quocthanh2694 commented Jun 12, 2020

It works for me with version:
"firebase": "^7.14.5", "@angular/fire": "^5.4.2",
and this code:

if (navigator && navigator.serviceWorker) {
            navigator.serviceWorker.addEventListener('message', this.onReceiveMsg.bind(this));
        }
onReceiveMsg(fcmMessage: FCMMessageRaw) {
        logger.debug('foreground', fcmMessage);
}

@hiepxanh
Copy link
Contributor

PR is coming #2497

@hiepxanh
Copy link
Contributor

PR is close, since that firebase have new update:

version 7.16 of firebase was fix this bug. Please update to the newest version and try this:
image

Remember to update your firebase in package.json. and the version must me matching with the firebase-messaging-sw.js or the notification will not fire in foreground

image

for who was confuse with firebase-messaging-sw.js you need to create a file and update the angular.json follow the instruction:

image

@fermdotnet
Copy link

fermdotnet commented Aug 8, 2020

7.17.1 and the same problem.
Thanks @NethajiV . You saved me hours and days!

constructor(private messagingSvc:AngularFireMessaging){
    if(navigator && navigator.serviceWorker)
      navigator.serviceWorker.addEventListener('message', this.onReceiveMsg.bind(this));
}

onReceiveMsg(event){
   if(event.data && event.data['firebase-messaging-msg-data']){
      const {data} = event.data['firebase-messaging-msg-data'];
      console.log({data});
   }
}

@MUKESHGUPTA-dev
Copy link

I m using firebase 7.22.1 version and @angular/fore 5.4.0 i m getting response when call API but not getting Pop-up Notification
i tried each solution mentioned here except using firebase version 7.6.0 please help me out.

@karthi-the-programmer
Copy link

this.angularFireMessaging.messaging.subscribe(
(_messaging: any) => {
// _messaging.onMessage = _messaging.onMessage.bind(_messaging);
_messaging._next = (payload: any) => {
console.log(payload);
};
_messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
}
);

which firebase and @angular/fire versions ?

@Seabird22
Copy link

Seabird22 commented Nov 16, 2020

For people still having this problem : We have this setup inside an Ionic / Angular app. We use the native cordova FCM plugin for mobile devices, but solely for developing purposes we wanted to have the notifications triggered in web too.

Notifications composer in Firebase console does not seem to work with AngularFire in web. We tried instead with a custom .NET testclient, and there it works. So if you are trying with the notifications compose: don't waste your time.

I am receiving both foreground and background notification messages with following setup:

(make sure you install "@angular/fire": "^6.0.5", "firebase": "8.0.2", )

firebase-messaging-sw.js

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

 // Initialize the Firebase app in the service worker by passing in
 // your app's Firebase config object.
 // https://firebase.google.com/docs/web/setup#config-object

 initializeFirebase();

function initializeFirebase() {
 var firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
  };
  // Initialize Firebase
  var firebaseApp = firebase.initializeApp(firebaseConfig);
  var messaging = firebase.messaging();

messaging.onBackgroundMessage(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize notification here
    const notificationTitle = 'Background Message Title';
    const notificationOptions = {
      body: 'Background Message body.',
      icon: '/firebase-logo.png'
    };
  
    self.registration.showNotification(notificationTitle,
      notificationOptions);
  });

app.component.ts (or wherever you want this in your app)

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

constructor(
    private firebaseMessaging: AngularFireMessaging,
  ) {
  }

this.platform.ready().then(() => {
       this.firebaseMessaging.requestPermission
      .pipe(mergeMapTo(this.firebaseMessaging.tokenChanges))
      .subscribe(
        (token) => { console.log('Permission granted!    Token:', token); },
        (error) => { console.error(error); },
      );
    this.firebaseMessaging.messages.subscribe(
      (message) => {
        console.log('Message received:', message);
      },
      (error) => { console.log("failed to subscribe to firebase messaging") }
    );
  }
    });

angular.json

 "architect": {
        "build": {
          "options": {
            "assets": [
              "src/firebase-messaging-sw.js"
            ],

@jamesdaniels
Copy link
Member

Things should be much better now, more to work on (out of box support with NGSW) but I we support VAPID_KEY and SERVICE_WORKER via DI tokens now.

@mafei-dev
Copy link

in the new versions use don't need to messaging.subscribe part.
Remove everything in the constructor, and update your package.json into the latest version. ant rut it.

@dodomui
Copy link

dodomui commented Jan 11, 2022

@mafei-dev
does afMessaging.messages.subscribe not working anymore?
I didn't receive any return when there's a new push notification come in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests