sta*_*af1 8 javascript firebase vue.js firebase-cloud-messaging
我一直致力于在我的 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 '@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)
我做错了什么?
我在 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)
| 归档时间: |
|
| 查看次数: |
2266 次 |
| 最近记录: |