Firebase Service Worker Error
Firebase Push Notifications.zip The Firebase Service worker works fine in the localhost and able to retrieve the device token in live when hosted it is causing this error
" An error occurred while retrieving token. Error: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: ServiceWorker script evaluation failed (messaging/failed-serviceworker-registration)"
I had a very similar issue, are you using https? Also use another browser to view the error it may actually spit out the path that it is looking for your SW.
I had a site: https://beta.tg.na/api/messenger/ The error said it failed to register default service worker the path however was looking in the root directory https://beta.tg.na moving the SW there worked :)
Hope this helps.
Also show us your SW, I initialized my firebase the wrong way, during registration the worker is seen has having an error then fails reg.
Here is the service worker file @TylerByte666
Service Worker File `importScripts('https://www.gstatic.com/firebasejs/4.1.1/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/4.1.1/firebase-messaging.js'); importScripts('https://www.gstatic.com/firebasejs/4.1.1/firebase.js');
/Replace the below lines with your Config From firebase ------------------------------------/ var config = { apiKey: "AIzaSyANY2-PYiM1baDa8GhfOWEaIzVuuVk5kvw", authDomain: "web-notifications-project.firebaseapp.com", databaseURL: "https://web-notifications-project.firebaseio.com", projectId: "web-notifications-project", storageBucket: "", messagingSenderId: "844162384804", }; firebase.initializeApp(config);
/Replace the below lines with your Config From firebase ------------------------------------/ const messaging = firebase.messaging();
//Added For Foreground Notifications Delete if not working Starts------------------------------- /* messaging.onMessage(function(payload) {
//const notificationTitle = payload.notification.title; const notificationOptions = { title: payload.notification.title, body: payload.notification.body, icon: payload.notification.icon, }; });*/
//Added For Foreground Notifications Delete if not working Starts-------------------------------
messaging.setBackgroundMessageHandler(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here const notificationTitle = payload.data.title;//'Background Message Title'; const notificationOptions = { // body: payload.data.body,//'Background Message body.', body: payload.notification.body , icon: payload.data.icon, image : payload.data.image, /* data:{ time: new Date(Date.now()).toString(), click_action : payload.data.click_action }*/ };
return self.registration.showNotification(notificationTitle,notificationOptions); });
self.addEventListener("notificationclick", (event) => { event.waitUntil(async function () { const allClients = await clients.matchAll({ includeUncontrolled: true }); let chatClient; let appUrl = 'https://www.google.com'; for (const client of allClients) { //here appUrl is the application url, we are checking it application tab is open if(client['url'].indexOf(appUrl) >= 0) { client.focus(); chatClient = client; break; } } if (!chatClient) { chatClient = await clients.openWindow(appUrl); } }()); });
/*self.addEventListener('notificationclick', function(event) { console.log('On notification click: ', event.notification.tag); event.notification.close();
// This looks to see if the current is already open and // focuses if it is event.waitUntil(clients.matchAll({ type: "window" }).then(function(clientList) { for (var i = 0; i < clientList.length; i++) { var client = clientList[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openWindow) return clients.openWindow('/'); })); });*/ /*self.addEventListener('notificationclick', function(e) { var notification = e.notification; var action_click = notification.data.click_action; var action = e.action; console.log("notificationclickcalled " + action_click);
e.notification.close();
e.waitUntil( clients.openWindow(action_click) );
return;
var notification = e.notification;
var primaryKey = notification.data.primaryKey;
var action = e.action;
console.log("notificationclickcalled " + primarykey);
if (action === 'close') {
notification.close();
} else {
clients.openWindow('https://dummypage.com');
notification.close();
}
});*/ /*self.addEventListener('notificationclick', function(event) { var action_click=event.notification.data.click_action; event.notification.close();
event.waitUntil(
clients.openWindow(action_click)
);
});*/
/*self.addEventListener('notificationclick', function(event) { event.notification.close(); event.waitUntil(clients.matchAll({ type: "window" }).then(function (clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == event.notification.data && 'focus' in client)
return client.focus();
}
if (clients.openWindow)
return clients.openWindow(event.notification.data);
}));
});*/`
I see your problem:
`var config = { apiKey: "AIzaSyANY2-PYiM1baDa8GhfOWEaIzVuuVk5kvw", authDomain: "web-notifications-project.firebaseapp.com", databaseURL: "https://web-notifications-project.firebaseio.com", projectId: "web-notifications-project", storageBucket: "", messagingSenderId: "844162384804", };
firebase.initializeApp(config); `
Must simple be:
`// Initialize the Firebase app in the service worker by passing in the // messagingSenderId.
firebase.initializeApp({ 'messagingSenderId': '844162384804' });`
Hope that helps 😘
Can I remove the config completely
On Thu, 17 Oct 2019 at 6:52 PM, TylerByte666 [email protected] wrote:
I see your problem:
`var config = { apiKey: "AIzaSyANY2-PYiM1baDa8GhfOWEaIzVuuVk5kvw", authDomain: "web-notifications-project.firebaseapp.com", databaseURL: "https://web-notifications-project.firebaseio.com", projectId: "web-notifications-project", storageBucket: "", messagingSenderId: "844162384804", };
firebase.initializeApp(config); `
Must simple be:
// Initialize the Firebase app in the service worker by passing in the // messagingSenderId. firebase.initializeApp({ 'messagingSenderId': '844162384804' });
Hope that helps 😘
— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/firebase/quickstart-js/issues/375?email_source=notifications&email_token=AKQ3OVLDTYP4FQMHV36DYWDQPBRIDA5CNFSM4I5PKZN2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEBQCL6I#issuecomment-543172089, or unsubscribe https://github.com/notifications/unsubscribe-auth/AKQ3OVI2UYH3RNZ7ILLV7DDQPBRIDANCNFSM4I5PKZNQ .
Keep everything as you have it. Just change Firebase App Initialization logic to mine. (I used your actual sender id)
Here's an example of a working SW one of mine :) It handles clicks without having to do anything fancy:
` importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-messaging.js'); importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-analytics.js');
// Initialize the Firebase app in the service worker by passing in the // messagingSenderId. firebase.initializeApp({ 'messagingSenderId': 'My-secret-hahahaha!' });
// Retrieve an instance of Firebase Messaging so that it can handle background // messages. const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here const notificationTitle = 'Background Message Title'; const notificationOptions = { body: 'Background Message body.', icon: '/firebase-logo.png' };
return self.registration.showNotification(notificationTitle, notificationOptions); }); `
Also remember to have "click_action" in your payload :) Mine sent via Postman:
Method: Post
{
"notification": {
"title": "Juice: New Internal Vacancy",
"body": "Click this notification to view it in juice 💖",
"icon": "firebase-logo.png",
"click_action": "http://www.google.com/",
"sound":"default"
},
"to": "my-secret-ahhahahahahaha"
}
So no need to handle the click_action seperately.Ok let me try it
On Thu, 17 Oct 2019 at 6:59 PM, TylerByte666 [email protected] wrote:
Keep everything as you have it. Just change Firebase App Initialization logic to mine. (I used your actual sender id)
Here's an example of a working SW one of mine :) It handles clicks without having to do that fancy:
` importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-app.js'); importScripts(' https://www.gstatic.com/firebasejs/7.1.0/firebase-messaging.js'); importScripts(' https://www.gstatic.com/firebasejs/7.1.0/firebase-analytics.js');
// Initialize the Firebase app in the service worker by passing in the // messagingSenderId. firebase.initializeApp({ 'messagingSenderId': 'My-secret-hahahaha!' });
// Retrieve an instance of Firebase Messaging so that it can handle background // messages. const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here const notificationTitle = 'Background Message Title'; const notificationOptions = { body: 'Background Message body.', icon: '/firebase-logo.png' };
return self.registration.showNotification(notificationTitle, notificationOptions); }); `
Also remember to have "click_action" in your payload :) Mine sent via Postman:
Method: Post { "notification": { "title": "Juice: New Internal Vacancy", "body": "Click this notification to view it in juice 💖", "icon": "firebase-logo.png", "click_action": "http://www.google.com/", "sound":"default" }, "to": "my-secret-ahhahahahahaha" }
— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/firebase/quickstart-js/issues/375?email_source=notifications&email_token=AKQ3OVKTFPFUCHZAUZWBPWLQPBSDLA5CNFSM4I5PKZN2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEBQDETA#issuecomment-543175244, or unsubscribe https://github.com/notifications/unsubscribe-auth/AKQ3OVJSPTDJ6VVTUMDOOL3QPBSDLANCNFSM4I5PKZNQ .
`importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-messaging.js'); importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase-analytics.js'); importScripts('https://www.gstatic.com/firebasejs/7.1.0/firebase.js');
firebase.initializeApp({"messagingSenderId" : "My Sender Key"});
/Replace the below lines with your Config From firebase ------------------------------------/ const messaging = firebase.messaging(); messaging.setBackgroundMessageHandler(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here const notificationTitle = payload.data.title;//'Background Message Title'; const notificationOptions = { // body: payload.data.body,//'Background Message body.', body: payload.notification.body , icon: payload.data.icon, image : payload.data.image, click_action: "http://www.google.com/", sound:"default" };
return self.registration.showNotification(notificationTitle,notificationOptions); });`
The above code is the one I need to use right @TylerByte666
What I meant about payload was in postman, you must not do the click_action in the SW itself rather the payload sent to your fcm:
here is a better formatted/ less confusing code sample that your SW should be: https://github.com/kenng/firebase-push-notification-demo/blob/master/firebase-messaging-sw.js
I got the click action working but it is opening my own website link (default) instead of google.com which I added in the payload @TylerByte666
I want to include a custom image as icon and open a custom url : https://www.google.com in click_action please help me to do this @TylerByte666
`messaging.setBackgroundMessageHandler(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); const notification = { title : "This is a Title", body : "This is a body", icon : 'firebase-logo.png', click_action : "https://www.google.com", sound : "default"
};
return self.registration.showNotification(title,notification);
});`
This is my code how can I include my own icon and click_action @TylerByte666
Sure :P
Simply add a link to the actual image to the the "icon" field of your payload.
You should be able to replace the current icon with an actual link that is accessible or ftp'd to your site: So upload the image you want ten replace the payload as such:
{
"notification": {
"title": "Juice: New Internal Vacancy",
"body": "Click this notification to view it in juice 💖",
"icon": "https://angular.io/assets/images/logos/angular/[email protected]",
"click_action": "https://google.com.na",
"sound":"default"
},
"to": "<Replace with your actual IID>"
}
@TylerByte666 I am sending the notification to the users subscribed to a topic, So how I add "to" . I am using these lines inside service worker file and not in postman
Mate I reckon it is time to close this issue here. We got your SW successfully registered.
Mate I reckon it is time to close this issue here. We got your SW successfully registered.
But the custom icon and click action still not working
Create a private repro of your current source, then add me as a member. But close this as your original issue has been solved and these hardworking firebase guys need a break ❤️ 🔥
On Mon, Oct 21, 2019 at 2:06 PM BharadhanVM [email protected] wrote:
but
Mate I reckon it is time to close this issue here. We got your SW successfully registered.
But the custom icon and click action still not working
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/firebase/quickstart-js/issues/375?email_source=notifications&email_token=AIV7HB3FL6KXHLJJIL4HKBDQPWLM7A5CNFSM4I5PKZN2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEB2CWFY#issuecomment-544484119, or unsubscribe https://github.com/notifications/unsubscribe-auth/AIV7HB76JFYG4ZMEAECR4MLQPWLM7ANCNFSM4I5PKZNQ .
Create a private repro of your current source, then add me as a member. But close this as your original issue has been solved and these hardworking firebase guys need a break ❤️ 🔥 … On Mon, Oct 21, 2019 at 2:06 PM BharadhanVM @.***> wrote: but Mate I reckon it is time to close this issue here. We got your SW successfully registered. But the custom icon and click action still not working — You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub <#375?email_source=notifications&email_token=AIV7HB3FL6KXHLJJIL4HKBDQPWLM7A5CNFSM4I5PKZN2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEB2CWFY#issuecomment-544484119>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AIV7HB76JFYG4ZMEAECR4MLQPWLM7ANCNFSM4I5PKZNQ .
Ok @TylerByte666