I am using FCM to send web notifications. i am getting this warning and clicking the notifications does not give the usual result (open the notification url). this is the Service-Worker code
importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': '<my senderid>'
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
self.addEventListener('notificationclick', function(event) {
event.notification.close();
var promise = new Promise(function(resolve) {
setTimeout(resolve, 1000);
}).then(function() {
return clients.openWindow(payload.data.locator);
});
event.waitUntil(promise);
});
var notificationTitle = payload.data.title;
var notificationOptions = {
body: payload.data.body,
icon: payload.data.icon
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
firebase-messaging-sw.js:108 Event handler of 'notificationclick' event must be added on the initial evaluation of worker script.
this is the warning message, 108 reffers to this line
self.addEventListener('notificationclick', function(event) {
this is on chrome version 55. on firefox, nothing is wrong and it runs perfectly normal. Thanks in advance.
You should move
self.addEventListener
outside the function
messaging.setBackgroundMessageHandler
So that you add the EventListener only once.
Your full code should look like
const messaging = firebase.messaging();
self.addEventListener('notificationclick', function(event) {
event.notification.close();
var promise = new Promise(function(resolve) {
setTimeout(resolve, 1000);
}).then(function() {
return clients.openWindow(event.data.locator);
});
event.waitUntil(promise);
});
messaging.setBackgroundMessageHandler(function(payload) {
var notificationTitle = payload.data.title;
var notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
locator:payload.data.locator
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With