简体   繁体   English

Web firebase.messaging().onMessage 未触发,但后台通知完美触发

[英]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.如果使用 firebase.messaging().onMessage 发送推送消息,我想在前台重新加载或触发某些事件,但它没有被触发。 I'm using firebase.mesaging.sw.js with background notification and it works correctly what is wrong with my code?我正在使用带有后台通知的 firebase.mesaging.sw.js 并且它可以正常工作我的代码有什么问题?

firebase.js 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 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.对此的简单解决方案是将您的Firebse更新到最新版本。

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.注意:一旦您更新了 firebase 库版本,那么 messagesSenderId 将无法在您的 firebase- messaging -sw.js文件中使用。 You have to provide all other params eg.您必须提供所有其他参数,例如。 apiKey, projectId, appId along with messagingSenderId . apiKey、projectId、appId以及messagesSenderId

  • If still not work.如果还是不行。 Clean your browser cache and re-register service worker.清理浏览器缓存并重新注册 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).将包含头文件的 JS 文件和 SW JS 文件中的 Firebase SDK 版本升级到最新版本(当前为 7.8.1)。
  2. Adding the entire firebaseConfig array to the SW firebase.initializeApp() , as the previous answer suggests.如前一个答案所示,将整个firebaseConfig数组添加到 SW firebase.initializeApp()
  3. Cleaning the Chrome cache from the Application > Clear Storage section in the Developer Tools.从开发人员工具中的应用程序 > 清除存储部分清除 Chrome 缓存。
  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.基本上,从更新的 Firebase SDK开始全新的开始似乎可以解决此类问题。

Still had the same issue in 2020. In my case it was like this: 2020 年仍然有同样的问题。就我而言,情况是这样的:

  • you need to have same versions in importScripts for background messages and in your app for foreground messages您需要在importScripts中为后台消息使用相同的版本,在您的应用程序中为前台消息使用相同的版本
  • call it after obtaining token for background service获取后台服务token后调用
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.你错过了很多东西,只有在调用 firebase 之前初始化它, onMessage 才会起作用。 Please follow this.请遵循此。 I have done it like this and it is working.我已经这样做了,它正在工作。

initialize firebase and get the token初始化 firebase 并获取令牌

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 Firebase function 和有效载荷类型

    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.我使用了 async 和 await 因为我们需要异步管理 firebase/firestore 操作。

fcm does not work in Incognito mode and safari browser fcm 在隐身模式和 safari 浏览器下不起作用

Same issue i was faced.我面临同样的问题。 In my case firebase version in "package.json" and "firebase-messaging-sw.js" importScripts version was different.就我而言, “package.json”“firebase-messaging-sw.js” importScripts 版本中的 firebase 版本不同。 After set same version in "firebase-messaging-sw.js" importScripts which was in "package.json" , my issue is resolved."package.json"中的 "firebase -messaging-sw.js" importScripts 中设置相同版本后,我的问题得到解决。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 不会为 eventSource 触发 onmessage 函数 - onmessage function is not fired for eventSource 未捕获的类型错误:firebase.messaging 不是函数 - Uncaught TypeError: firebase.messaging is not a function Firebase云消息传递-调用firebase.messaging()时出错 - Firebase Cloud Messaging - Error calling firebase.messaging() chrome.runtime.onMessage侦听器永远不会被触发 - chrome.runtime.onMessage listener is never fired websocket客户端中的onmessage事件没有被解雇 - onmessage event in websocket client is not getting fired firebase.messaging:无法读取未定义的属性“getNotificationPermission_” - firebase.messaging: Cannot read property 'getNotificationPermission_' of undefined 类型错误:firebase.messaging 不是 node.js 中的函数 - TypeError: firebase.messaging is not a function in node.js Firebase 消息传递 onMessage 仅在窗口中可用 - Firebase messaging onMessage only available in a window 每次刷新使用Firebase Cloud Messaging + React和firebase.messaging()。getToken()都是不同的 - Using Firebase Cloud Messaging + React and firebase.messaging().getToken() is different each refresh Firebase 云消息传递:通知图标背景仅在第二次尝试时有效 - Firebase Cloud Messaging: Notification Icon Background is only working on second attempt
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM