相关疑难解决方法(0)

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

我一直致力于在我的 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 …
Run Code Online (Sandbox Code Playgroud)

javascript firebase vue.js firebase-cloud-messaging

8
推荐指数
1
解决办法
2266
查看次数