I'm using Firebase service worker for web push notification. Currently, I am facing this error:
Uncaught FirebaseError: Messaging: This method is available in a Window context. (messaging/only-available-in-window).
I am using a website on my desktop to register the SW. How do I resolve this issue?
Error stack I'm getting in console.
browserErrorMessage: "Failed to register a ServiceWorker: ServiceWorker script evaluation failed"
code :"messaging/failed-serviceworker-registration"
message :"Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: ServiceWorker script evaluation failed (messaging/failed-serviceworker-registration)."
stack: "FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: ServiceWorker script evaluation failed (messaging/failed-serviceworker-registration).↵ at https://www.gstatic.com/firebasejs/3.7.0/firebase.js:555:225"
__proto__: Error
Thank you
firebase-messaging-sw. js is a must and should be present in the host root directory. This is required to setup background notification handler when browser is not in focus or in background.
The FCM JavaScript API lets you receive notification messages in web apps running in browsers that support the Push API. This includes the browser versions listed in this support matrix and Chrome extensions via the Push API. The FCM SDK is supported only in pages served over HTTPS.
A sender ID: set in the code of your app. Android Studio uses automatically the Sender ID of your Firebase Project. If you are still using GCM, you have probably set manually the sender ID in the code of your app. The sender ID identifies your app to Firebase Cloud Messaging when it asks for a token.
This method should be there in the main javascript file, NOT in service worker. Service Worker works in the background.
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
Please keep the Line, it is very much required in the SW:
const messaging = firebase.messaging();
The Issue is not Messaging itself, but most likely a part of it that is used in your SW which however is not supported in there.
Sadly I can't see your Code from the SW, but what was causing this issue for me was that I implemented the following to receive Messages, while the Website is in foreground:
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
This however requires the window context and needs to be implemented in the actual website, not the SW. For me this caused the Error you described.
Try using Firebases sample SW. This is doing everything it needs to and allows you to receive Notifications in the Background.
If you want to share your SW code, we could have a look at it.
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