I am using FCM web app notification for send notification to browser.My code below.
var config = {
apiKey: "<API-KEY>",
authDomain: "<AUTH-DOMAIN>.firebaseapp.com",
databaseURL: "<DATABASE>.firebaseio.com",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDERID>",
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function(){
console.log("GRANTED");
console.log(messaging.getToken());
return messaging.getToken();
})
.then(function(token){
console.log(token);
})
.catch(function(err){
console.log('Error Occurred.' + err)
});
messaging.setBackgroundMessageHandler(function(payload){
const title = "Hello World";
const option = { body: payload.data.status }
return self.registration.showNotification(title,option);
});
It is working fine and generating token on the chrome's localhost server but not working on my hosting server.
I got the following error with my hosting server.
Error Occurred.FirebaseError: Messaging: We are unable to register the default service worker. The operation is insecure. (messaging/failed-serviceworker-registration).
Please guide me if anybody have any idea about this.
2021 working procedure with create-react-app
In /public folder create file firebase-messaging-sw.js with the following code:
// Scripts for firebase and firebase messaging
importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js");
// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
apiKey: "YOURDATA",
authDomain: "YOURDATA",
projectId: "YOURDATA",
storageBucket: "YOURDATA",
messagingSenderId: "YOURDATA",
appId: "YOURDATA",
measurementId: "YOURDATA",
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function(payload) {
console.log("Received background message ", payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
Now in app.js or wherever you needed add this code.
/*firebase daniel start*/
import { initializeApp } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "YOURDATA",
authDomain: "YOURDATA",
projectId: "YOURDATA",
storageBucket: "YOURDATA",
messagingSenderId: "YOURDATA",
appId: "YOURDATA",
measurementId: "YOURDATA",
};
const fapp = initializeApp(firebaseConfig);
const messaging = getMessaging(fapp);
getToken(messaging, {
vapidKey:
"YOURKEY",
})
.then((currentToken) => {
if (currentToken) {
console.log("Firebase Token", currentToken);
} else {
// Show permission request UI
console.log(
"No registration token available. Request permission to generate one."
);
// ...
}
})
.catch((err) => {
console.log("An error occurred while retrieving token. ", err);
// ...
});
onMessage(messaging, (payload) => {
console.log("Message received. ", payload);
// ...
});
/*firebase daniel end*/
create firebase-messaging-sw.js in your root folder and paste the code in it.
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);
});
}
Try to add the below sample in your firebase-messaging-sw.js
and put firebase-messaging-sw.js
inside your public folder in react app.
// Scripts for firebase and firebase messaging
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing the generated config
var firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function(payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
Although there are multiple threads and closed issues for this error, this thread comes up at top of google result if this error is directly copied from console to search, hence sharing my experience here makes sense.
As the other answers suggest:
firebase-messaging-sw.js
is publicly available at the host rootEven after checking all these, I got the same error.
So finally resort to google docs and this time I read carefully here
From Firebase v9, they moved to compat as mentioned in this commit
So, the import scripts inside firebase-messaging-sw.js
are now:
importScripts('https://www.gstatic.com/firebasejs/<v9+>/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/<v9+>/firebase-messaging-compat.js');
where <v9+>
is the Firebase SDK version above 9
Thats it done!!
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