简体   繁体   中英

Web firebase.messaging().onMessage not fired, but background notification perfectly fired

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

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

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM