angularfire icon indicating copy to clipboard operation
angularfire copied to clipboard

Not receiving FCM messages

Open BradyShober opened this issue 8 years ago • 48 comments

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.

BradyShober avatar Sep 30 '18 19:09 BradyShober

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

kobvel avatar Dec 18 '18 16:12 kobvel

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);
    })
}

thongnx6 avatar Dec 30 '18 07:12 thongnx6

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

fmandres92 avatar Jan 31 '19 22:01 fmandres92

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

Shifs avatar Mar 29 '19 04:03 Shifs

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.

BradyShober avatar Mar 29 '19 05:03 BradyShober

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!

CodeByBryan avatar Apr 09 '19 19:04 CodeByBryan

Any updates here? Is this project still maintained?

alihalabyah avatar Aug 20 '19 07:08 alihalabyah

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.

Thomas0921 avatar Oct 08 '19 03:10 Thomas0921

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));

lancelynyrd avatar Oct 14 '19 15:10 lancelynyrd

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

sgallard avatar Oct 17 '19 21:10 sgallard

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

azhararmar avatar Oct 18 '19 02:10 azhararmar

@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

lancelynyrd avatar Oct 18 '19 05:10 lancelynyrd

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

azhararmar avatar Oct 18 '19 16:10 azhararmar

@lancelynyrd solution worked for me

khetho avatar Nov 12 '19 10:11 khetho

@azhararmar U save my ass.

link4hy avatar Nov 18 '19 02:11 link4hy

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

Dhamo-krish avatar Dec 10 '19 08:12 Dhamo-krish

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

parth181195 avatar Jan 17 '20 08:01 parth181195

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

AlMorton avatar Jan 28 '20 11:01 AlMorton

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');
      })
  }
}

rtsdemo123 avatar Jan 30 '20 15:01 rtsdemo123

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 avatar Feb 02 '20 16:02 vincepunkrock