Firebase 云消息传递前台通知在 Vue 中不起作用

sta*_*af1 8 javascript firebase vue.js firebase-cloud-messaging

我一直致力于在我的 Vue PWA 应用程序中集成 FCM。到目前为止,我已经设法让后台通知正常工作,但是当应用程序在前台不起作用时处理通知。这是我的代码。

src/App.vue

import firebase from './plugins/firebase'

export default {
  // Other stuff here...

  methods: {
    prepareFcm () {
      var messaging = firebase.messaging()
      messaging.usePublicVapidKey(this.$store.state.fcm.vapidKey)
      messaging.getToken().then(async fcmToken => {
        this.$store.commit('fcm/setToken', fcmToken)
        messaging.onMessage(payload => {
          window.alert(payload)
        })
      }).catch(e => {
        this.$store.commit('toast/setError', 'An error occured to push notification.')
      })
    }
  },

  mounted () {
    this.prepareFcm()
  }
}
Run Code Online (Sandbox Code Playgroud)

public/firebase-messaging-sw.js

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

firebase.initializeApp({
  messagingSenderId: '123456789'
})

const messaging = firebase.messaging()

messaging.setBackgroundMessageHandler(function (payload) {
  return self.registration.showNotification(payload)
})
Run Code Online (Sandbox Code Playgroud)

src/plugins/firebase.js

import firebase from '@firebase/app'
import '@firebase/messaging'
// import other firebase stuff...

const firebaseConfig = {
  apiKey: '...',
  authDomain: '...',
  databaseURL: '...',
  projectId: '...',
  storageBucket: '...',
  messagingSenderId: '123456789',
  appId: '...'
}

firebase.initializeApp(firebaseConfig)

export default firebase
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

sta*_*af1 2

我在 StackOverflow 的另一个 QA 中找到了解决方案(由于某种原因我找不到了)。

结果你必须使用 Firebase API v7.8.0 而不是像当时文档所说的 5.5.6 。所以前两行public/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')
Run Code Online (Sandbox Code Playgroud)