I’m trying to request a Notification permission token with Firebase Cloud Messaging with JavaScript. My current code works, but as explained in the code comment, there seems to be a strange behavior regarding the steps.
What should happen:
- User clicks on send reminders html button,
- browser asks for notifications permissions,
- user clicks on allow,
- user receives the
current_token
value.
What is actually happening:
- User clicks on send reminders html button,
- browser asks for notifications permissions,
- user clicks on allow,
- user doesn’t receive the
current_token
value, - user has to click on send reminders html button again,
- this time the user receives the
current_token
value (of course without the need of click on allow, because the permissions were previously granted).
To my best understanding, when messaging.getToken
is executed, the code inside then(function(current_token)
is only reached if the user has previously granted notifications permissions, but this should happen in one single action.
Here’s my current code:
html
<button type="button" id="remind_me">send reminders</button>
<script src="https://www.gstatic.com/firebasejs/10.0.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.0.0/firebase-messaging-compat.js"></script>
javascript
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/firebase-messaging-sw.js', {
scope: '/'
}).then(function(registration) {
console.log('fcm: service worker registered successfully');
}).catch(function(error) {
console.error('fcm: service worker registration failed:', error);
});
navigator.serviceWorker.ready.then(function(registration) {
console.log('fcm: service worker is ready');
window.onload = function() {
console.log('fcm: service worker is ready and page is fully loaded');
if (navigator.serviceWorker.controller) {
console.log('fcm: service worker active and controlling page');
sw_ready();
} else {
console.log('fcm: service worker ready but not yet controlling page');
registration.addEventListener('controllerchange', function () {
console.log('fcm: service worker active and controlling page');
sw_ready();
});
}
};
});
}
// default sw ready
let sw_ready = function () {
$('#remind_me').click(function(e) {
// request permission for firebase cloud messaging
console.log('fcm: attemping to get token');
messaging.getToken({
vapidKey: config.firebase.messaging // this is a valid vapidKey
}).then(function(current_token) {
// THIS PART OF THE CODE IS ONLY REACHED
// THE 2ND TIME #remind_me IS CLICKED ON
// check token
if (current_token) {
console.log('fcm: token accquired', current_token);
} else {
// request denied
console.log('fcm: user denied permission for notications');
}
}).catch(function(error) {
// error while retrieving token
});
});
}
Any ideas? Thanks!