I have used FCM as per this https://firebase.google.com/docs/cloud-messaging/js/client
, and I am getting below error:
FirebaseError {code: "messaging/failed-serviceworker-registration", message: "Messaging: We are unable to register the default s…ed (messaging/failed-serviceworker-registration).", browserErrorMessage: "Failed to register a ServiceWorker: ServiceWorker script evaluation failed", stack: "FirebaseError: Messaging: We are unable to registe…tp://localhost:3000/static/js/0.chunk.js:57713:26"}
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 http://localhost:3000/static/js/0.chunk.js:57713:26"
__proto__: Error
What I am doing:
Created a react app by create-react-app pushnotification
Downloaded firebase using sudo npm install --save firebase in my project
created a firebase.js file in src folder of the react app with below content
import firebase from 'firebase'; var config = { apiKey: "MY_KEY", authDomain: "MY_Domain", databaseURL: "MY_DBurl", projectId: "My_ProjectID", storageBucket: "My_StorageBucket", messagingSenderId: "My_Msg_id" }; firebase.initializeApp(config); const messaging = firebase.messaging(); messaging.requestPermission().then(function(){ console.log("Have Permission"); }).catch(function(error){ console.log(error); })
and when I refresh my web app it asks for the permission like below:
So far everything is working, now I am updating my firebase.js file like below to send push notification:
import firebase from 'firebase';
var config = {
apiKey: "MY_KEY",
authDomain: "MY_Domain",
databaseURL: "MY_DBurl",
projectId: "My_ProjectID",
storageBucket: "My_StorageBucket",
messagingSenderId: "My_Msg_id"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.requestPermission().then(function(){
console.log("Have Permission");
return messaging.getToken();
}).then(function(token){
console.log(token)
}).catch(function(error){
console.log(error);
});
messaging.onMessage(function(payload){
console.log(payload);
})
also I have create a firebase-messaging-sw.js file with below content:
import firebase from 'firebase';
var config = {
apiKey: "MY_KEY",
authDomain: "MY_Domain",
databaseURL: "MY_DBurl",
projectId: "My_ProjectID",
storageBucket: "My_StorageBucket",
messagingSenderId: "My_Msg_id"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
In my public folder and now when I do a page refresh I get above error:
For some reason, doing firebase integrations take days because of their incomplete/unclear docs (at least for me.). Sharing what worked for me.
My setup:
What worked for me:
-src
-public
--firebase-messaging-sw.js
--index.html
Yes, had to put firebase-messaging-sw.js inside 'public' instead of root folder. Maybe it has to be at same depth as of the main entry point file (index.html)
<script src="https://www.gstatic.com/firebasejs/8.2.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.2/firebase-messaging.js"></script>
<script type="text/javascript">
try {
if (!firebase.apps.length) {
const firebaseConfig = { //from firebase project setting
};
firebase.initializeApp(firebaseConfig);
}
const messaging = firebase.messaging();
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
const notificationTitle = 'OnMessage Title';
const notificationOptions = {
body: 'OnMessage body.'
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
function resetUI() {
const vapidKey = '<>'; //from firebase project settings
messaging.getToken({ vapidKey: vapidKey }).then((currentToken) => {
console.log("currentToken", currentToken);
if (currentToken) {
//..
} else {
console.log('No registration token available. Request permission to generate one.');
requestPermission();
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
}
function requestPermission() {
console.log('Requesting permission...');
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
resetUI();
} else {
console.log('Unable to get permission to notify.');
}
});
}
resetUI();
} catch (e) {
console.log("firebase startup error ", e);
}
</script>
Later, I was able to move the above code in script to App.js.
importScripts('https://www.gstatic.com/firebasejs/8.2.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.2/firebase-messaging.js');
const vapidKey = '<>'; //from firebase project settings
const firebaseConfig = { //from firebase project settings
...
};
if (!firebase.apps.length) {
try {
firebase.initializeApp(firebaseConfig);
} catch (e) {
console.log("sw error", e)
}
}
let messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log('firebase Received background message ', JSON.stringify(payload));
// const notificationTitle = 'Background Message Title';
// const notificationOptions = {
// body: 'Background Message body.',
// // icon: '../assets/icon.png'
// };
// return self.registration.showNotification(notificationTitle,
// notificationOptions);
});
I think that you should configure Web credentials.
messaging.usePublicVapidKey("set your key here")
See:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.