Im tryin to get Firebase FCM working in my React project(using webpack )
When trying to getToken() using:
messaging.requestPermission()
.then(func
If you are using firebase, react and you scaffold with create react app things you need to do:
(based on @Humble Student answer)
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function(registration) {
firebase.messaging().useServiceWorker(registration);
}).catch(function(err) {
console.log('Service worker registration failed, error:', err);
});
}
Hope that helps!
For those using create-react-app, you can create the firebase-messaging-sw.js
inside public
folder and, on index.js
add:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
}).catch(function(err) {
console.log('Service worker registration failed, error:', err);
});
}
If you are using create-react-app. Add firebase-messaging-sw.js to your public folder and rebuild. firebase-messaging-sw.js can be an empty file
I have the same exact problem as in the original question, and I have gone through all kinds of solutions without any luck over the past 3 days. I am using ReactJS and Webpack. I've tried to include file called firebase-messaging-sw.js in my root folder, but it does nothing.
Someone, please help, since the firebase notification is a much needed feature in the project I am developing...
EDIT.
I managed to solve the registration problem by installing a webpack plugin called sw-precache-webpack-plugin. This plugin autogenerates a service-worker file for you into your build directory.
The issue here was that my project setup didn't 'see' service worker file.
Since i'm using node with express, the firebase-messaging-sw.js had to be place where express is picking up static content. In my case line:
server.use(Express.static(path.join(__dirname, '../..', 'dist')));
means that I had to put firebase-messaging-sw.js into /dist folder.
In order to receive messages, you will need to create a file called firebase-messaging-sw.js
. See the section Handle messages when your web app is in the foreground in the Firebase documentation:
In order to receive the onMessage event, your app must define the Firebase messaging service worker in
firebase-messaging-sw.js
.