我正在开发一个应该能够接收FCM消息的chrome扩展程序。要获取我的 FCM 令牌,我使用以下代码
messaging.requestPermission().then(function(permission) {
messaging.getToken().then(function(current_token) {
if(current_token) {
//update user token
console.log('token', current_token);
} else {
// you don't have permission to show notifications
// detect whether they are blocked or not, then show your custom UI
}
}).catch(function(err) {
// retrieving token failed, analyze the error
console.error('retrieving token failed, analyze the error', err);
});
}
但问题是我得到的permission
是未定义的类型,然后我没有从getToken()
得到任何结果,没有空标记,没有错误,什么都没有。
好的,多亏了@Mr.Rebot评论,我发现这很可能是一个chrome错误,解决方法是在Chrome通知设置中手动将扩展程序列入白名单。您的扩展链接看起来像chrome-extension://<extension-id>/
.
要获取令牌,需要做两件事:
- 在项目根目录中创建空
firebase-messaging-sw.js
,并将其作为背景脚本包含在manifest.json
中。例如,我这样做了:
"background": {
"scripts": [
"js/firebase-app.js",
"js/firebase-messaging.js",
"firebase-messaging-sw.js",
"js/background.js"
],
"persistent": false
}
- 现在在 manifest.json 中添加
"notifications"
权限。我的看起来像:
"permissions": [
"storage",
"tabs",
"notifications"
]
现在messaging.getToken()
(background.js
(甚至可以不使用messaging.requestPermission()
即可正常工作。