步骤1)安装依赖项
npm install firebase
npm install @nuxtjs/firebase
步骤2)在您的项目根文件夹中创建一个名为serviceWorker.js
的文件。
self.addEventListener('push', function (e) {
data = e.data.json();
var options = {
body: data.notification.body,
icon: data.notification.icon,
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: '2'
},
};
步骤3)将您的
nuxt.config.js
配置如下。
将以下行添加到文件顶部。
const fs = require('fs')
更新您的模块数组以包含 Firebase 凭据。
[
'@nuxtjs/firebase',
{
config: {
apiKey: "<yourKey>",
authDomain: "<yourAuthDomain>",
projectId: "<yourProjectId>",
storageBucket: "<yourStorageBucket>",
messagingSenderId: "<yourMessagingSenderId>",
appId: "<yourAppId>",
measurementId: ",<yourMeasurementId>"
},
onFirebaseHosting: false,
services: {
messaging: {
createServiceWorker: true,
fcmPublicVapidKey: '<yourFCMPublicVapidKey>',
inject: fs.readFileSync('./serviceWorker.js')
}
}
}
]
第四步 > 最后...将其添加到您的index.js或layout文件中。
async mounted() {
const currentToken = await this.$fire.messaging.getToken()
const data = JSON.stringify({
notification: {
title: 'firebase',
body: 'firebase is awesome',
click_action: 'http://localhost:3000/',
icon: 'http://localhost:3000/assets/images/brand-logo.png'
},
to: currentToken
})
const config = {
method: 'post',
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Content-Type': 'application/json',
'Authorization': 'key=<yourServerKey>'
},
data
};
const response = await axios(config)
this.$fire.messaging.onMessage((payload) => {
console.info('Message received: ', payload)
})
this.$fire.messaging.onTokenRefresh(async () => {
const refreshToken = await this.$fire.messaging.getToken()
console.log('Token Refreshed',refreshToken)
})
}
如需了解更多细节和步骤,您可以访问文章。