I am currently working on implementing web push notifications using Firebase. Unfortunately, when attempting to access messaging.getToken()
, I encounter an error stating "messaging is undefined." Below is the code snippet I am utilizing:
private messaging = firebase.messaging(); //declaration
this.messaging.requestPermission().then(function () {
console.log('Notification permission granted.');
this.messaging.getToken().then(function (currentToken) {
console.log(currentToken, 'currentToken');
if (currentToken) {
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
}
}).catch(function (err) {
console.log('An error occurred while retrieving token. ', err);
});
}).catch(function (err) {
console.log('Unable to get permission to notify.', err);
});
The issue arises with the first log statement displaying "Notification permission granted," followed immediately by executing the catch block displaying "Unable to get permission to notify." Despite adding the firebase-messaging-sw.js
file to my root directory and linking it in index.html, as well as testing over HTTPS, the following error persists:
Notification permission granted.
home.component.ts:113 Unable to get permission to notify.
TypeError: Cannot read property 'messaging' of undefined
at home.component.ts:95
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
at Object.onInvoke (core.js:3760)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
at zone.js:872
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3751)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
If you have any suggestions or solutions, they would be greatly appreciated. Thank you.