我正在为 JavaScript 设置一个 Firebase 客户端。当要求通知权限时,我允许它,但它仍然返回false
.
firebase.initializeApp(firebaseConfig);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
//Request permission to receive notifications
messaging.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// ...
} else {
console.log('Unable to get permission to notify.');
}
});
当我单击允许时,我在控制台中收到以下内容"无法获得通知权限"。
根据文档:
如果授予权限,则承诺将解析。否则,承诺将被拒绝并显示错误。
因此,与其检查传递的参数,不如检查承诺是解析还是拒绝:
messaging.requestPermission().then(() => {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// ...
}).catch((err) => {
console.log('Unable to get permission to notify.');
});
话虽如此,根据文档,requestPermission()
已被弃用,应替换为Notification.requestPermission()
.那个看起来更像你尝试的方式:
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// ...
} else {
console.log('Unable to get permission to notify.');
}
});