我一直致力于在我的 Vue PWA 应用程序中集成 FCM。到目前为止,我已经设法让后台通知正常工作,但是当应用程序在前台不起作用时处理通知。这是我的代码。
src/App.vueimport 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.jsimportScripts('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.jsimport firebase from '@firebase/app'
import …Run Code Online (Sandbox Code Playgroud)