12

I want to reload or trigger some event in foregrounf if push message is sent with firebase.messaging().onMessage, but it not fired. I'm using firebase.mesaging.sw.js with background notification and it works correctly what is wrong with my code?

firebase.js

const config = {
  apiKey: "x",
  projectId: "x",
  storageBucket: "x",
  messagingSenderId: "x"
};

firebase.initializeApp(config);

const msg = firebase.messaging()
msg.requestPermission()
  .then(() => {
    return msg.getToken()
  })
  .then((token) => {
  })
  .catch((err) => {
  })

msg.onMessage(function(payload) {
  alert("Foreground message fired!")
  console.log(payload)
});

firebase.messaging.sw.js

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

const config = {
  apiKey: "x",
  projectId: "x",
  storageBucket: 'x',
  messagingSenderId: "x"
};

firebase.initializeApp(config);
const msg = firebase.messaging()

msg.setBackgroundMessageHandler(function(payload) {
  let options = {
    body: payload.data.body,
    icon: payload.data.icon
  }

  return self.registration.showNotification(payload.data.title, options);

});

I don't know what is wrong with my code

5 Answers 5

11

Simple solution to this is update your Firebse to latest version.

Eg.

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

Note: Once you have updated your firebase libraries versions then messagingSenderId will not work in your firebase-messaging-sw.js file. You have to provide all other params eg. apiKey, projectId, appId along with messagingSenderId.

  • If still not work. Clean your browser cache and re-register service worker.

For more details you can refer to this solution

3
  • Sorry but it seems both statements are false. Background notifications keep arriving with just the messagingSenderId in the SW, and neither the upgrade in the Firebase APIs seem to fix anything. The onMessage event just won't trigger.
    – andreszs
    Commented Feb 18, 2020 at 14:26
  • 1
    @andreszs Was facing same issue with firebasejs/7.0.0 version. Not triggering onMasage event. I have updated my firebase version to latest. Then i was facing issue kind of project id is missing in SW. So I have passed all other details. Then everything was worked. Commented Feb 19, 2020 at 6:03
  • Thanks, I admit that adding the entire firebaseConfig to the initializeApp method in the SW as you stated, plus cleaning the Chrome data and cache and re-registering the notifications finally fixed the problem. You could add the cache cleaning and re-registration suggestion to expand your answer.
    – andreszs
    Commented Feb 19, 2020 at 16:58
5

Still had the same issue in 2020. In my case it was like this:

  • you need to have same versions in importScripts for background messages and in your app for foreground messages
  • call it after obtaining token for background service
firebaseApp.messaging().getToken().then((currentToken) => {
  if (currentToken) {
    console.log(currentToken)
  } else {
    // Show permission request.
    console.log(
      'No Instance ID token available. Request permission to generate one.')
  }
  /** When app is active */
  firebase.messaging().onMessage((payload) => {
    console.log(payload)
  }, e => {
    console.log(e)
  })
})
1
  • thanks running onMessage after getToken worked for me
    – Huiting
    Commented Mar 20, 2021 at 14:25
3

For anyone else with this problem, I finally solved it by:

  1. Upgrading the Firebase SDK version in both header-included JS files and the SW JS file to latest (currently, that would be 7.8.1).
  2. Adding the entire firebaseConfig array to the SW firebase.initializeApp(), as the previous answer suggests.
  3. Cleaning the Chrome cache from the Application > Clear Storage section in the Developer Tools.
  4. Deleting the previous registration token from my database.
  5. Blocking and unblocking notifications from the browser to force a new token generation.

Basically, a total fresh start with updated Firebase SDK seems to fix issues like this.

1

You are missing lots of things and onMessage will only work if firebase is initialized before calling it. Please follow this. I have done it like this and it is working.

initialize firebase and get the token

export class BrowserFcmProvider {
export const FIREBASE_CONFIG = {
 apiKey: "****",
 authDomain: "****",
 databaseURL: "****",
 projectId: "****",
 storageBucket: "****",
 messagingSenderId: "****",
 appId: "****"
}

firebase.initializeApp(FIREBASE_CONFIG);

async webGetToken() {
 try {
   const messaging = firebase.messaging();
   await messaging.requestPermission();
   const token = await messaging.getToken();
   let uuidTemp = new DeviceUUID().get();
   return this.saveTokenToFireStoreFromWeb(token, uuidTemp)

 } catch (e) {
   console.log(e);
 }
}

saveTokenToFireStoreFromWeb(token, uuid) {
  try {
     const docData = {
     token: token,
     device_type: 'web',
     uuid: uuid
     }
    const devicesRef = this.db.collection('devices')
    return devicesRef.doc(uuid).set(docData);
  } catch (e) {
    console.log(e, 'saveTokenError');
  }
}

showMessage() {
  try {
    const messaging = firebase.messaging();
    messaging.onMessage((payload) => {
    console.log(payload);
    })
  } catch (e) {
    console.log(e)
  }
}
}

And calling the method while app loads like this

  async configureFirebaseForBrowser(res) {
      await this.bfcm.webGetToken();
      this.bfcm.showMessage();
  }

Firebase function and payload type

    const payloadWeb = {
            title: title,
            body: body,
            data: {
                title: title,
                body: body
            },
            tokens: uniqueDevicesTokenArrayWeb,
        }

  const responseWeb = await admin.messaging().sendMulticast(payloadWeb);
  console.log(responseWeb.successCount + ' notifications has been sent to Web successfully');

I have used async and await as we need to manage firebase/firestore operations asynchronously.

fcm does not work in Incognito mode and safari browser

6
  • $scope.init = (startDate, endDate, role, moderation) => { webGetToken(); showMessage(); } I have used your example and it still didn't work, the requestPermission is granted but onMessage function isn't fired
    – Kuro Neko
    Commented Oct 15, 2019 at 8:18
  • Did you get any error? In which framework you are using this? Did you able to initialize firebase propeprly? const firebaseIntialise = firebase.initializeApp(FIREBASE_CONFIG); console.log(firebaseIntialise); what did you get? Commented Oct 15, 2019 at 8:54
  • i use laravel with node js, my firebaseInitialize is working properly, and if i put it on a variable and console it, you'll see an object with INTERNAL, firebase, isDeleted,options and many more
    – Kuro Neko
    Commented Oct 15, 2019 at 10:47
  • Both laravel and nodejs work for the server-side. Why you use two? Can you put it on GitHub so that I can look into and fix it. Commented Oct 16, 2019 at 5:57
  • U need change the SDK version in service worker to "7.1.0" importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-app.js') importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-messaging.js') Commented Jan 13, 2020 at 15:01
1

Same issue i was faced. In my case firebase version in "package.json" and "firebase-messaging-sw.js" importScripts version was different. After set same version in "firebase-messaging-sw.js" importScripts which was in "package.json", my issue is resolved.

Before change

 **"package.json"**
 
 "firebase": "^8.2.1",
 
  **"firebase-messaging-sw.js"**

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

After change

 **"package.json"**

 "firebase": "^8.2.1",

 **"firebase-messaging-sw.js"**

 importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
1
  • I have these version same, currently 8.9.1 But I cannot get the notification to print to the console. Eve tho I managed to invoke default popup for push notif after sending that notif directly from FCM console...Any suggestions? I can share code anywhere...
    – Wrapper
    Commented Aug 12, 2021 at 23:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.