带有Firebase云消息传递的Vue PWA无法正常工作 [英] Vue pwa with firebase cloud messaging not working properly
问题描述
尝试以下代码:
navigator.serviceWorker.register('service-worker.js')
.then((registration) => {
const messaging = firebase.messaging().useServiceworker(registration)
console.log(messaging)
messaging.requestPermission().then(function () {
console.log('Notification permission granted.')
messaging.getToken().then(function (currentToken) {
if (currentToken) {
console.log(currentToken)
}
})
})
})
我的清单:
{
"name": "Herot-Eyes",
"short_name": "herot-eyes",
"gcm_sender_id": "103953800507",
"icons": [
{
"src": "/static/img/icons/herot-eyes-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/static/img/icons/herot-eyes-512x512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "/static/img/icons/apple-touch-icon-180x180.png",
"sizes": "180x180",
"type": "image/png"
}
],
"start_url": "/",
"display": "fullscreen",
"orientation": "portrait",
"background_color": "#000000",
"theme_color": "#2196f3"
}
出了什么问题?我的console.log(messaging)返回工厂错误,如下:
what is going wrong? my console.log(messaging) is returning a factory error, the following:
bad-push-set:用于存储/查找的FCM推送集不是 有效的推送设置字符串." bad-scope
bad-push-set : "The FCM push set used for storage / lookup was not not a valid push set string." bad-scope
服务工作者范围必须是至少包含一个的字符串 字符." bad-sender-id
"The service worker scope must be a string with at least one character." bad-sender-id
",请确保正确设置了"messagingSenderId" 选项传递到firebase.initializeApp()."无效订阅
"Please ensure that 'messagingSenderId' is set correctly in the options passed into firebase.initializeApp()." bad-subscription
订阅必须是有效的PushSubscription."坏令牌: 用于存储/查找的FCM令牌不是有效的令牌字符串." 坏密钥
"The subscription must be a valid PushSubscription." bad-token : "The FCM Token used for storage / lookup was not a valid token string." bad-vapid-key
公共VAPID密钥不是具有65个字节的Uint8Array." bg-handler-function-expected
"The public VAPID key is not a Uint8Array with 65 bytes." bg-handler-function-expected
"setBackgroundMessageHandler()的输入必须是一个函数." 删除未找到的范围
"The input to setBackgroundMessageHandler() must be a function." delete-scope-not-found
无法对服务工作者范围进行删除尝试 因为找不到范围." delete-token-not-found
"The deletion attempt for service worker scope could not be performed as the scope was not found." delete-token-not-found
无法尝试删除令牌作为令牌 找不到." failed-delete-vapid-key
"The deletion attempt for token could not be performed as the token was not found." failed-delete-vapid-key
无法删除VAPID密钥." 服务人员注册失败
"The VAPID key could not be deleted." failed-serviceworker-registration
我们无法注册默认服务工作者. {$ browserErrorMessage}"删除令牌失败
"We are unable to register the default service worker. {$browserErrorMessage}" failed-to-delete-token
无法删除当前保存的令牌."订阅失败
"Unable to delete the currently saved token." get-subscription-failed
尝试获取任何现有的Push时发生错误 订阅".不正确的gcm-sender-id
"There was an error when trying to get any existing Push Subscriptions." incorrect-gcm-sender-id
"请将您的网络应用清单的'gcm_sender_id'值更改为 "103953800507"以使用Firebase消息传递." invalid-delete-token
"Please change your web app manifest's 'gcm_sender_id' value to '103953800507' to use Firebase messaging." invalid-delete-token
您必须将有效令牌传递到deleteToken()中,即来自 getToken()."invalid-public-vapid-key
"You must pass a valid token into deleteToken(), i.e. the token from getToken()." invalid-public-vapid-key
公共VAPID密钥必须是字符串."保存的令牌无效
"The public VAPID key must be a string." invalid-saved-token
无法访问已保存令牌的详细信息." 没有fcm令牌可以重新订阅
"Unable to access details of the saved token." no-fcm-token-for-resubscribe
"找不到FCM令牌,因此无法重新订阅. 下次访问时必须重新订阅用户." no-sw-in-reg
"Could not find an FCM token and as a result, unable to resubscribe. Will have to resubscribe the user on next visit." no-sw-in-reg
即使服务人员注册成功, 访问服务人员本身的问题." 没有窗口客户端到味精
"Even though the service worker registration was successful, there was a problem accessing the service worker itself." no-window-client-to-msg
试图向不存在的窗口客户端发送消息." 通知被阻止
"An attempt was made to message a non-existant window client." notifications-blocked
通知已被阻止."只能在软件中使用
"Notifications have been blocked." only-available-in-sw
此方法在服务工作者上下文中可用." 窗口中唯一可用
"This method is available in a service worker context." only-available-in-window
此方法在Window上下文中可用."权限被阻止
"This method is available in a Window context." permission-blocked
未授予并阻止了所需的权限." 权限默认值
"The required permissions were not granted and blocked instead." permission-default
必需的权限没有被授予,而是被取消了." 公用密钥解密失败
"The required permissions were not granted and dismissed instead." public-vapid-key-decryption-failed
公共VAPID密钥在解密时不等于65个字节." 应该被覆盖
"The public VAPID key did not equal 65 bytes when decrypted." should-be-overriden
此方法应由扩展类覆盖." sw-reg冗余
"This method should be overriden by extended classes." sw-reg-redundant
用于推送的服务人员变得多余." sw-registration-expected
"The service worker being used for push was made redundant." sw-registration-expected
服务人员注册是预期的输入." 令牌订阅失败
"A service worker registration was the expected input." token-subscribe-failed
在将用户订阅到FCM时发生了问题:{$ message}" 令牌订阅没有推送设置
"A problem occured while subscribing the user to FCM: {$message}" token-subscribe-no-push-set
"FCM在获取FCM令牌时返回了无效的响应." 令牌订阅无令牌
"FCM returned an invalid response when getting an FCM token." token-subscribe-no-token
"FCM订阅用户推送时未返回任何令牌." 令牌取消订阅失败
"FCM returned no token when subscribing the user to push." token-unsubscribe-failed
退订FCM用户时发生问题:{$ message}" 令牌更新失败
"A problem occured while unsubscribing the user from FCM: {$message}" token-update-failed
从FCM更新用户时发生问题:{$ message}" 令牌更新无令牌
"A problem occured while updating the user from FCM: {$message}" token-update-no-token
"FCM更新用户推送时未返回任何令牌." 无法重新订阅
"FCM returned no token when updating the user to push." unable-to-resubscribe
"重新订阅FCM令牌以进行推送时出错 消息传递.下次访问时将不得不重新订阅用户. {$ message}"浏览器不支持
"There was an error while re-subscribing the FCM token for push messaging. Will have to resubscribe the user on next visit. {$message}" unsupported-browser
此浏览器不支持使用Firebase所需的API SDK." use-sw-before-get-token
"This browser doesn't support the API's required to use the firebase SDK." use-sw-before-get-token
您必须先调用useServiceWorker(),然后再调用getToken()以确保 您的服务人员已被使用."
"You must call useServiceWorker() before calling getToken() to ensure your service worker is used."
推荐答案
配置为服务器以接收通知
在公用文件夹中,将以下行添加到 manifest.json :
{
//...manifest properties
"gcm_sender_id": "103953800507" <--- add this line to the file
}
注意:如果不是使用Vue Cli创建的项目,请手动创建 manifest.json 文件.(感谢@natghi)
Note: if the project wasn't created using Vue Cli, manually create the manifest.json file. (Thanks @natghi)
firebase-messaging-sw.js
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
var config = {
messagingSenderId: <Sender ID>
};
firebase.initializeApp(config);
let messaging = firebase.messaging();
在您的main.js文件中添加以下代码
In your main.js file add the following code
var config = {
apiKey: <API_KEY>,
authDomain: <DOMAIN>,
databaseURL: <DATABASE_URL>,
projectId: <PROJECT_ID>,
storageBucket: <STORAGE_BUCKET>,
messagingSenderId: <SENDER_ID>
};
firebase.initializeApp(config);
Vue.prototype.$messaging = firebase.messaging()
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then((registration) => {
Vue.prototype.$messaging.useServiceWorker(registration)
}).catch(err => {
console.log(err)
})
接收通知
然后在您的App.vue中,将此代码添加到created()函数中
Receive notifications
Then in your App.vue, add this code to the created() function
created() {
var config = {
apiKey: <API_KEY>,
authDomain: <DOMAIN>,
databaseURL: <DATABASE_URL>,
projectId: <PROJECT_ID>,
storageBucket: <STORAGE_BUCKET>,
messagingSenderId: <SENDER_ID>
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(() => firebase.messaging().getToken())
.then((token) => {
console.log(token) // Receiver Token to use in the notification
})
.catch(function(err) {
console.log("Unable to get permission to notify.", err);
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
}
发送通知
更新
const admin = require("firebase-admin")
var serviceAccount = require("./certificate.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const Messaging = admin.messaging()
var payload = {
webpush: {
notification: {
title: "Notification title",
body: "Notification info",
icon: 'http://i.imgur.com/image.png',
click_action: "http://yoursite.com/redirectPage"
},
},
topic: "Doente_" + patient.Username
};
return Messaging.send(payload)
旧版本
然后,在邮递员中,您执行以下请求
Older version
Then, in postman you do the following request
POST /v1/projects/interact-f1032/messages:send HTTP/1.1
Host: fcm.googleapis.com
Authorization: Bearer <SENDER_TOKEN>
Content-Type: application/json
{
"message":{
"token" : The token that was in the console log,
"notification" : {
"body" : "This is an FCM notification message!",
"title" : "FCM Message"
}
}
}
发件人令牌
在您的后端中,使用以下代码,其中文件"certificate.json"位于是在Firebase仪表板中找到的( https://firebase.google.com/docs /cloud-messaging/js/client -生成密钥对)
const {google} = require('googleapis');
function getAccessToken() {
return new Promise(function(resolve, reject) {
var key = require('./certificate.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
["https://www.googleapis.com/auth/firebase",
"https://www.googleapis.com/auth/cloud-platform"],
null
);
jwtClient.authorize(function(err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
getAccessToken().then(senderToken => console.log(senderToken))
senderToken用于Authorization标头上以发送通知
The senderToken is used on the Authorization header to send a notification
这篇关于带有Firebase云消息传递的Vue PWA无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!