Here is my whole code:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js";
import { getMessaging, getToken } from "https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging.js";
//This data is filled correctly just clearing it here for the question
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "t",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const bbFirebase = initializeApp(firebaseConfig);
const messaging = getMessaging();
// Add the public key generated from the console here.
getToken(messaging, { vapidKey: 'I_HAVE_PLACED_VALID_KEY_HERE' }).then((currentToken) => {
if (currentToken) {
console.log("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);
// ...
});
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: '/firebase-logo.png'
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
function requestPermission() {
console.log('Requesting permission...');
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve a registration token for use with FCM.
// In many cases once an app has been granted notification permission,
// it should update its UI reflecting this.
resetUI();
} else {
console.log('Unable to get permission to notify.');
}
});
}
So when I execute this code I can generate a token. I see the token clearly and all good there. However I have this error:
Uncaught TypeError: messaging.onBackgroundMessage is not a function
at firebase.js:31:11
Any idea why I can this error and how can I at least console.log() print the incoming notifications?
The onBackgroundMessage() is a top level function just like getToken() in the new functional syntax imported from firebase/messaging/sw as mentioned in the documentation.
import { getMessaging, onMessage } from 'firebase/messaging'
import { onBackgroundMessage } from 'firebase/messaging/sw'
onBackgroundMessage(messaging, (payload) => {
// ...
})
I´m having trouble with this too but if you paste this code in firebase-messaging-sw.js and that file is in the root of firebase hosting it works.
// Import and configure the Firebase SDK
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts('/__/firebase/9.2.0/firebase-app-compat.js');
importScripts('/__/firebase/9.2.0/firebase-messaging-compat.js');
importScripts('/__/firebase/init.js');
const messaging = firebase.messaging();
/**
* Here is is the code snippet to initialize Firebase Messaging in the Service
* Worker when your app is not hosted on Firebase Hosting.
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/9.2.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.2.0/firebase-messaging-compat.js');
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
apiKey: 'api-key',
authDomain: 'project-id.firebaseapp.com',
databaseURL: 'https://project-id.firebaseio.com',
projectId: 'project-id',
storageBucket: 'project-id.appspot.com',
messagingSenderId: 'sender-id',
appId: 'app-id',
measurementId: 'G-measurement-id',
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
**/
// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// Keep in mind that FCM will still show notification messages automatically
// and you should use data messages for custom notifications.
// For more info see:
// https://firebase.google.com/docs/cloud-messaging/concept-options
messaging.onBackgroundMessage(function(payload) {
// console.log('[firebase-messaging-sw.js] Received background message ', payload);
console.log('[firebase-messaging-sw.js] PAYLOAD NOTIFICATION: ', payload.notification);
// Customize notification here
const notificationTitle = payload.notification.title
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.image
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
Related
Here is my code:
<script src="/js/firebase.js" type="module"></script>
firebase.js:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js";
import { getMessaging, getToken} from "https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging.js";
import { onBackgroundMessage } from "https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging-sw.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const bbFirebase = initializeApp(firebaseConfig);
const messaging = getMessaging();
// Add the public key generated from the console here.
getToken(messaging, { vapidKey: 'MY_KEY_HERE' }).then((currentToken) => {
if (currentToken) {
console.log("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);
// ...
});
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: '/firebase-logo.png'
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
function requestPermission() {
console.log('Requesting permission...');
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve a registration token for use with FCM.
// In many cases once an app has been granted notification permission,
// it should update its UI reflecting this.
resetUI();
} else {
console.log('Unable to get permission to notify.');
}
});
}
firebase-messaging-sw.js:
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.16.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging-compat.js');
/*
Initialize the Firebase app in the service worker by passing in the messagingSenderId.
*/
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "G-JK625X6GX2"
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
console.log(payload.notification.title);
});
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Received background message ');
console.log(payload.notification.title);
});
When I execude the code I see the output of console.log("TOKEN: " + currentToken);
So token is generated. When I try to send notification to this token I am monitoring the browser console but no notification seems to be received. Any idea why ?
P.S.
I am trying this locally on my Mac using Valet as service for the domain.
I want to send Firebase web notifications from FCM to PWA app. I tried doing that and ended up with the below error.
I've gone through sever links in StackOverflow but no luck.
Firebase web push notification Service worker issue
FirebaseError: Messaging: We are unable to register the default service worker
A bad HTTP response code (404) was received when fetching the script.
An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('https://dms-uat.xxxxxx.net/firebase-cloud-messaging-push-scope') with script ('https://dms-uat.xxxxxx.net/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).
at rt. (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:31316)
at https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:1935
at Object.throw (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:2040)
at i (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:834)
Both index.html and firebase-messaging-sw.js files are currently in the domain/messaging folder.
I was taught that firebase-messaging-sw.js file should be in the root folder which means domain/firebase-messaging-sw.js, is this correct? If so, how could I make it done?
Service worker in browser:
Here is my firebase-messaging-sw.js file.
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/init.js');
const messaging = firebase.messaging();
var firebaseConfig = {
apiKey: "xxxxxxxx-l7lKJ6nAtsmyfXRX5gXcl2_0a3Y",
authDomain: "xxxxxx-9fa59.firebaseapp.com",
databaseURL: "https://xxxxxx-9fa59.firebaseio.com",
projectId: "xxxxx-9fa59",
storageBucket: "xxxxxx-9fa59.appspot.com",
messagingSenderId: "123456789",
appId: "1:215883024305:web:f1b6b2148bd185584d1f90",
measurementId: "G-MP1GQDZ18D"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//firebase.analytics();
/**
* Here is is the code snippet to initialize Firebase Messaging in the Service
* Worker when your app is not hosted on Firebase Hosting.
// [START initialize_firebase_in_sw]
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
apiKey: 'api-key',
authDomain: 'project-id.firebaseapp.com',
databaseURL: 'https://project-id.firebaseio.com',
projectId: 'project-id',
storageBucket: 'project-id.appspot.com',
messagingSenderId: 'sender-id',
appId: 'app-id',
measurementId: 'G-measurement-id',
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
// [END initialize_firebase_in_sw]
**/
// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
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);
});
// [END background_handler]
Here is my index.html
<!--
Copyright (c) 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Firebase Cloud Messaging Example</title>
<!-- Material Design Theming -->
<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
<link rel="stylesheet" href="./main.css">
<link rel="manifest" href="./manifest.json">
</head>
<body>
<div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-header">
<!-- Header section containing title -->
<header class="mdl-layout__header mdl-color-text--white mdl-color--light-blue-700">
<div class="mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-grid">
<div class="mdl-layout__header-row mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--8-col-desktop">
<h3>Firebase Cloud Messaging</h3>
</div>
</div>
</header>
<main class="mdl-layout__content mdl-color--grey-100">
<div class="mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-grid">
<!-- Container for the Table of content -->
<div class="mdl-card mdl-shadow--2dp mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--12-col-desktop">
<div class="mdl-card__supporting-text mdl-color-text--grey-600">
<!-- div to display the generated Instance ID token -->
<div id="token_div" style="display: none;">
<h4>Instance ID Token</h4>
<p id="token" style="word-break: break-all;"></p>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
onclick="deleteToken()">
Delete Token
</button>
</div>
<!-- div to display the UI to allow the request for permission to
notify the user. This is shown if the app has not yet been
granted permission to notify. -->
<div id="permission_div" style="display: none;">
<h4>Needs Permission</h4>
<p id="token"></p>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
onclick="requestPermission()">
Request Permission
</button>
</div>
<!-- div to display messages received by this app. -->
<div id="messages"></div>
</div>
</div>
</div>
</main>
</div>
<!-- Import and configure the Firebase SDK -->
<!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
<!-- If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup -->
<!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-auth.js"></script>
<!-- <script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-firestore.js"></script>-->
<script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js"></script>
<!-- <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script> -->
<script>
var firebaseConfig = {
apiKey: "xxxxxxxx-l7lKJ6nAtsmyfXRX5gXcl2_0a3Y",
authDomain: "xxxxx-9fa59.firebaseapp.com",
databaseURL: "https://xxxxx-9fa59.firebaseio.com",
projectId: "xxxxx-9fa59",
storageBucket: "xxxxx-9fa59.appspot.com",
messagingSenderId: "123456789",
appId: "1:215883024305:web:f1b6b2148bd185584d1f90",
measurementId: "G-MP1GQDZ18D"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//firebase.analytics();
// [START get_messaging_object]
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
// [END get_messaging_object]
// [START set_public_vapid_key]
// Add the public key generated from the console here.
messaging.usePublicVapidKey('BDTDxT_59kRHBjDTBwnDvFQcdy8Y8A8NvjFFzW2aMo27raPODdeX89pSBA6pxerBbmpBXaLxiadjiNHTDmComhs');
// [END set_public_vapid_key]
// IDs of divs that display Instance ID token UI or request permission UI.
const tokenDivId = 'token_div';
const permissionDivId = 'permission_div';
// [START refresh_token]
// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(() => {
messaging.getToken().then((refreshedToken) => {
console.log('Token refreshed.');
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
setTokenSentToServer(false);
// Send Instance ID token to app server.
sendTokenToServer(refreshedToken);
// [START_EXCLUDE]
// Display new Instance ID token and clear UI of all previous messages.
resetUI();
// [END_EXCLUDE]
}).catch((err) => {
console.log('Unable to retrieve refreshed token ', err);
showToken('Unable to retrieve refreshed token ', err);
});
});
// [END refresh_token]
// [START receive_message]
// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
// `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// [START_EXCLUDE]
// Update the UI to include the received message.
appendMessage(payload);
// [END_EXCLUDE]
});
// [END receive_message]
function resetUI() {
clearMessages();
showToken('loading...');
// [START get_token]
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then((currentToken) => {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
// [END get_token]
}
function showToken(currentToken) {
// Show token in console and UI.
const tokenElement = document.querySelector('#token');
tokenElement.textContent = currentToken;
}
// Send the Instance ID token your application server, so that it can:
// - send messages back to this app
// - subscribe/unsubscribe the token from topics
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer()) {
console.log('Sending token to server...' + currentToken);
// TODO(developer): Send the current token to your server.
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again ' +
'unless it changes');
}
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') === '1';
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? '1' : '0');
}
function showHideDiv(divId, show) {
const div = document.querySelector('#' + divId);
if (show) {
div.style = 'display: visible';
} else {
div.style = 'display: none';
}
}
function requestPermission() {
console.log('Requesting permission...');
// [START request_permission]
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// [START_EXCLUDE]
// In many cases once an app has been granted notification permission,
// it should update its UI reflecting this.
resetUI();
// [END_EXCLUDE]
} else {
console.log('Unable to get permission to notify.');
}
});
// [END request_permission]
}
function deleteToken() {
// Delete Instance ID token.
// [START delete_token]
messaging.getToken().then((currentToken) => {
messaging.deleteToken(currentToken).then(() => {
console.log('Token deleted.');
setTokenSentToServer(false);
// [START_EXCLUDE]
// Once token is deleted update UI.
resetUI();
// [END_EXCLUDE]
}).catch((err) => {
console.log('Unable to delete token. ', err);
});
// [END delete_token]
}).catch((err) => {
console.log('Error retrieving Instance ID token. ', err);
showToken('Error retrieving Instance ID token. ', err);
});
}
// Add a message to the messages element.
function appendMessage(payload) {
const messagesElement = document.querySelector('#messages');
const dataHeaderELement = document.createElement('h5');
const dataElement = document.createElement('pre');
dataElement.style = 'overflow-x:hidden;';
dataHeaderELement.textContent = 'Received message:';
dataElement.textContent = JSON.stringify(payload, null, 2);
messagesElement.appendChild(dataHeaderELement);
messagesElement.appendChild(dataElement);
}
// Clear the messages element of all children.
function clearMessages() {
const messagesElement = document.querySelector('#messages');
while (messagesElement.hasChildNodes()) {
messagesElement.removeChild(messagesElement.lastChild);
}
}
function updateUIForPushEnabled(currentToken) {
showHideDiv(tokenDivId, true);
showHideDiv(permissionDivId, false);
showToken(currentToken);
}
function updateUIForPushPermissionRequired() {
showHideDiv(tokenDivId, false);
showHideDiv(permissionDivId, true);
}
resetUI();
</script>
</body>
</html>
I didn't much changes except firebase-ap.js, firebase-mesaging.js files.
Please let me know if you need more info.
firebase.messaging needs a SW registration. If you don't specify a registration, it creates a new registration at root level and needs firebase-messaging-sw.js file at root
useServiceWorker is deprecated
Registration can be passed when you getToken():
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("./firebase-messaging-sw.js")
.then(function(registration) {
console.log("Registration successful, scope is:", registration.scope);
messaging.getToken({vapidKey: 'YOUR_VAPID_KEY', serviceWorkerRegistration : registration })
.then((currentToken) => {
if (currentToken) {
console.log('current token for client: ', currentToken);
// Track the token -> client mapping, by sending to backend server
// show on the UI that permission is secured
} else {
console.log('No registration token available. Request permission to generate one.');
// shows on the UI that permission is required
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// catch error while creating client token
});
})
.catch(function(err) {
console.log("Service worker registration failed, error:" , err );
});
}
Here is the answer, this useServiceWorker (...) saves my day
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function(registration) {
console.log("Service Worker Registered");
messaging.useServiceWorker(registration);
});
}
First, add these 2 scripts in your index.html file
<script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.7.0/firebase-messaging.js"></script>
Then in your public/firebase-messaging-sw.js file, copy following code
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: "XXX",
authDomain: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('setBackgroundMessageHandler background message ', payload);
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true
})
.then(windowClients => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(payload);
}
})
.then(() => {
return self.registration.showNotification("my notification title");
});
return promiseChain;
});
Now got to your App.js file, and in react's lifecycle function componentDidMount, add following code.
componentDidMount =() => {
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
firebase.messaging().requestPermission().then(async () => {
return messaging.getToken();
}).then((token) => {
console.log('now the token is>>>>>>>>>>>>>>>>', token)
}).catch((err) => {
console.log('catch errror>>>>>>>>>>>>>', err)
})
}
here firebaseConfig var, is the config object
var firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
};
If you gets error like firebase not defined, add this comment, before the componentDidMount lifecycle method.
/*global firebase*/
Hope it would for you.
I want to send Firebase web notifications from FCM to PWA app. I tried doing that and ended up with the below error.
I've gone through sever links in StackOverflow but no luck.
Firebase web push notification Service worker issue
FirebaseError: Messaging: We are unable to register the default service worker
A bad HTTP response code (404) was received when fetching the script.
An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('https://dms-uat.xxxxxx.net/firebase-cloud-messaging-push-scope') with script ('https://dms-uat.xxxxxx.net/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).
at rt. (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:31316)
at https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:1935
at Object.throw (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:2040)
at i (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:834)
Both index.html and firebase-messaging-sw.js files are currently in the domain/messaging folder.
I was taught that firebase-messaging-sw.js file should be in the root folder which means domain/firebase-messaging-sw.js, is this correct? If so, how could I make it done?
Service worker in browser:
Here is my firebase-messaging-sw.js file.
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/init.js');
const messaging = firebase.messaging();
var firebaseConfig = {
apiKey: "xxxxxxxx-l7lKJ6nAtsmyfXRX5gXcl2_0a3Y",
authDomain: "xxxxxx-9fa59.firebaseapp.com",
databaseURL: "https://xxxxxx-9fa59.firebaseio.com",
projectId: "xxxxx-9fa59",
storageBucket: "xxxxxx-9fa59.appspot.com",
messagingSenderId: "123456789",
appId: "1:215883024305:web:f1b6b2148bd185584d1f90",
measurementId: "G-MP1GQDZ18D"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//firebase.analytics();
/**
* Here is is the code snippet to initialize Firebase Messaging in the Service
* Worker when your app is not hosted on Firebase Hosting.
// [START initialize_firebase_in_sw]
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
apiKey: 'api-key',
authDomain: 'project-id.firebaseapp.com',
databaseURL: 'https://project-id.firebaseio.com',
projectId: 'project-id',
storageBucket: 'project-id.appspot.com',
messagingSenderId: 'sender-id',
appId: 'app-id',
measurementId: 'G-measurement-id',
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
// [END initialize_firebase_in_sw]
**/
// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
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);
});
// [END background_handler]
Here is my index.html
<!--
Copyright (c) 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Firebase Cloud Messaging Example</title>
<!-- Material Design Theming -->
<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
<link rel="stylesheet" href="./main.css">
<link rel="manifest" href="./manifest.json">
</head>
<body>
<div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-header">
<!-- Header section containing title -->
<header class="mdl-layout__header mdl-color-text--white mdl-color--light-blue-700">
<div class="mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-grid">
<div class="mdl-layout__header-row mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--8-col-desktop">
<h3>Firebase Cloud Messaging</h3>
</div>
</div>
</header>
<main class="mdl-layout__content mdl-color--grey-100">
<div class="mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-grid">
<!-- Container for the Table of content -->
<div class="mdl-card mdl-shadow--2dp mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--12-col-desktop">
<div class="mdl-card__supporting-text mdl-color-text--grey-600">
<!-- div to display the generated Instance ID token -->
<div id="token_div" style="display: none;">
<h4>Instance ID Token</h4>
<p id="token" style="word-break: break-all;"></p>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
onclick="deleteToken()">
Delete Token
</button>
</div>
<!-- div to display the UI to allow the request for permission to
notify the user. This is shown if the app has not yet been
granted permission to notify. -->
<div id="permission_div" style="display: none;">
<h4>Needs Permission</h4>
<p id="token"></p>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
onclick="requestPermission()">
Request Permission
</button>
</div>
<!-- div to display messages received by this app. -->
<div id="messages"></div>
</div>
</div>
</div>
</main>
</div>
<!-- Import and configure the Firebase SDK -->
<!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
<!-- If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup -->
<!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-auth.js"></script>
<!-- <script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-firestore.js"></script>-->
<script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js"></script>
<!-- <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script> -->
<script>
var firebaseConfig = {
apiKey: "xxxxxxxx-l7lKJ6nAtsmyfXRX5gXcl2_0a3Y",
authDomain: "xxxxx-9fa59.firebaseapp.com",
databaseURL: "https://xxxxx-9fa59.firebaseio.com",
projectId: "xxxxx-9fa59",
storageBucket: "xxxxx-9fa59.appspot.com",
messagingSenderId: "123456789",
appId: "1:215883024305:web:f1b6b2148bd185584d1f90",
measurementId: "G-MP1GQDZ18D"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//firebase.analytics();
// [START get_messaging_object]
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
// [END get_messaging_object]
// [START set_public_vapid_key]
// Add the public key generated from the console here.
messaging.usePublicVapidKey('BDTDxT_59kRHBjDTBwnDvFQcdy8Y8A8NvjFFzW2aMo27raPODdeX89pSBA6pxerBbmpBXaLxiadjiNHTDmComhs');
// [END set_public_vapid_key]
// IDs of divs that display Instance ID token UI or request permission UI.
const tokenDivId = 'token_div';
const permissionDivId = 'permission_div';
// [START refresh_token]
// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(() => {
messaging.getToken().then((refreshedToken) => {
console.log('Token refreshed.');
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
setTokenSentToServer(false);
// Send Instance ID token to app server.
sendTokenToServer(refreshedToken);
// [START_EXCLUDE]
// Display new Instance ID token and clear UI of all previous messages.
resetUI();
// [END_EXCLUDE]
}).catch((err) => {
console.log('Unable to retrieve refreshed token ', err);
showToken('Unable to retrieve refreshed token ', err);
});
});
// [END refresh_token]
// [START receive_message]
// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
// `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// [START_EXCLUDE]
// Update the UI to include the received message.
appendMessage(payload);
// [END_EXCLUDE]
});
// [END receive_message]
function resetUI() {
clearMessages();
showToken('loading...');
// [START get_token]
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then((currentToken) => {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
// [END get_token]
}
function showToken(currentToken) {
// Show token in console and UI.
const tokenElement = document.querySelector('#token');
tokenElement.textContent = currentToken;
}
// Send the Instance ID token your application server, so that it can:
// - send messages back to this app
// - subscribe/unsubscribe the token from topics
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer()) {
console.log('Sending token to server...' + currentToken);
// TODO(developer): Send the current token to your server.
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again ' +
'unless it changes');
}
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') === '1';
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? '1' : '0');
}
function showHideDiv(divId, show) {
const div = document.querySelector('#' + divId);
if (show) {
div.style = 'display: visible';
} else {
div.style = 'display: none';
}
}
function requestPermission() {
console.log('Requesting permission...');
// [START request_permission]
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// [START_EXCLUDE]
// In many cases once an app has been granted notification permission,
// it should update its UI reflecting this.
resetUI();
// [END_EXCLUDE]
} else {
console.log('Unable to get permission to notify.');
}
});
// [END request_permission]
}
function deleteToken() {
// Delete Instance ID token.
// [START delete_token]
messaging.getToken().then((currentToken) => {
messaging.deleteToken(currentToken).then(() => {
console.log('Token deleted.');
setTokenSentToServer(false);
// [START_EXCLUDE]
// Once token is deleted update UI.
resetUI();
// [END_EXCLUDE]
}).catch((err) => {
console.log('Unable to delete token. ', err);
});
// [END delete_token]
}).catch((err) => {
console.log('Error retrieving Instance ID token. ', err);
showToken('Error retrieving Instance ID token. ', err);
});
}
// Add a message to the messages element.
function appendMessage(payload) {
const messagesElement = document.querySelector('#messages');
const dataHeaderELement = document.createElement('h5');
const dataElement = document.createElement('pre');
dataElement.style = 'overflow-x:hidden;';
dataHeaderELement.textContent = 'Received message:';
dataElement.textContent = JSON.stringify(payload, null, 2);
messagesElement.appendChild(dataHeaderELement);
messagesElement.appendChild(dataElement);
}
// Clear the messages element of all children.
function clearMessages() {
const messagesElement = document.querySelector('#messages');
while (messagesElement.hasChildNodes()) {
messagesElement.removeChild(messagesElement.lastChild);
}
}
function updateUIForPushEnabled(currentToken) {
showHideDiv(tokenDivId, true);
showHideDiv(permissionDivId, false);
showToken(currentToken);
}
function updateUIForPushPermissionRequired() {
showHideDiv(tokenDivId, false);
showHideDiv(permissionDivId, true);
}
resetUI();
</script>
</body>
</html>
I didn't much changes except firebase-ap.js, firebase-mesaging.js files.
Please let me know if you need more info.
firebase.messaging needs a SW registration. If you don't specify a registration, it creates a new registration at root level and needs firebase-messaging-sw.js file at root
useServiceWorker is deprecated
Registration can be passed when you getToken():
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("./firebase-messaging-sw.js")
.then(function(registration) {
console.log("Registration successful, scope is:", registration.scope);
messaging.getToken({vapidKey: 'YOUR_VAPID_KEY', serviceWorkerRegistration : registration })
.then((currentToken) => {
if (currentToken) {
console.log('current token for client: ', currentToken);
// Track the token -> client mapping, by sending to backend server
// show on the UI that permission is secured
} else {
console.log('No registration token available. Request permission to generate one.');
// shows on the UI that permission is required
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// catch error while creating client token
});
})
.catch(function(err) {
console.log("Service worker registration failed, error:" , err );
});
}
Here is the answer, this useServiceWorker (...) saves my day
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function(registration) {
console.log("Service Worker Registered");
messaging.useServiceWorker(registration);
});
}
First, add these 2 scripts in your index.html file
<script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.7.0/firebase-messaging.js"></script>
Then in your public/firebase-messaging-sw.js file, copy following code
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: "XXX",
authDomain: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('setBackgroundMessageHandler background message ', payload);
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true
})
.then(windowClients => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(payload);
}
})
.then(() => {
return self.registration.showNotification("my notification title");
});
return promiseChain;
});
Now got to your App.js file, and in react's lifecycle function componentDidMount, add following code.
componentDidMount =() => {
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
firebase.messaging().requestPermission().then(async () => {
return messaging.getToken();
}).then((token) => {
console.log('now the token is>>>>>>>>>>>>>>>>', token)
}).catch((err) => {
console.log('catch errror>>>>>>>>>>>>>', err)
})
}
here firebaseConfig var, is the config object
var firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
};
If you gets error like firebase not defined, add this comment, before the componentDidMount lifecycle method.
/*global firebase*/
Hope it would for you.
I am trying to send out a push notification from a web based client to similar clients. I have managed to implement on the receiving end, however I am unable to send due to the following error:
Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: Failed to fetch. Error code: undefined".
My firebase initialization file:
import firebase from "firebase";
var firebaseConfig = {
apiKey: "AIzaSyBhQV8zHeo7piFalXcA14v6hV*****",
authDomain: "*****-demo-a82ca.firebaseapp.com",
databaseURL: "https://*****-demo-a82ca.firebaseio.com",
projectId: "*****demo-a82ca",
storageBucket: "",
messagingSenderId: "52526034576",
appId: "1:52526034576:web:7b271318a*****"
};
// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
export default firebaseApp.firestore();
export const firebaseMessaging = firebaseApp.messaging()
firebaseMessaging.initializeApp(firebaseConfig);
And the js file doing the sending:
import { firebaseMessaging } from "#/firebase/init";
sendNotification() {
this.broadcastingAnnouncement = true;
console.log("Selected audience: ", this.selectedAudience);
var registrationToken =
"ezdWAWsKo48:APA91bF************"; //Client to receive the notification
var message = {
data: {
title: "Hello World",
body: "Test message"
},
token: registrationToken
};
firebaseMessaging
.messaging()
.send(message)
.then(response => {
// Response is a message ID string.
console.log("Successfully sent notification:", response);
})
.catch(error => {
console.log("Error sending message:", error);
});
}
What could be my issue here? (I have confirmed that my api key is correct)
I'm not sure, but it seems you are trying to use client side SDK to send push messages, although you should use Admin SDK.
The code above anyway looks curiously:
Why do you call initializeApp() on you firebaseMessaging object, which doesn't have such method
Why do you call firebaseMessaging.messaging(), firebaseMessaging object is already a Messaging instance
How do I receive notifications in the react app and not in the browser?
At moment I receive notifications on :
firebase-messaging-sw.js
code of firebase-messaging-sw.js:
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
var config = {
apiKey: "myapikey",
authDomain: "thank-you-posta.firebaseapp.com",
databaseURL: "https://thank-you-posta.firebaseio.com",
projectId: "thank-you-posta",
storageBucket: "thank-you-posta.appspot.com",
messagingSenderId: "403125505139"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
self.addEventListener('notificationclick', function(event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('http://localhost:7000/#/messages/')
);
});
Code in Layout:
var config = {
apiKey: "myapikey",
authDomain: "thank-you-posta.firebaseapp.com",
databaseURL: "https://thank-you-posta.firebaseio.com",
projectId: "thank-you-posta",
storageBucket: "thank-you-posta.appspot.com",
messagingSenderId: "403125505139"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
messaging.getToken()
.then(function(currentToken) {
if (currentToken) {
console.log(currentToken);
_this.setState({
pushToken: currentToken
});
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
}
})
.catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
});
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
My problem is that I want to receive notifications to make a dropdown with all the notifications in Layout.
Thx All.
If you want to show these notifications in your app then you have to create a notifications component in your app. The simplest way to do this is to use something like toaster https://github.com/tomchentw/react-toastr
Basically, you add a toaster snippet in your root component and then you feed toaster your notifications. It is unclear from your code where you are storing the notifications that you send to your service worker, but wherever they are just redirect them to toast. If you are creating new messages from the firebase console then redirect them to toast when you specify .onMessage
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// the container bit below is from the toast demo in the link above
container.success(payload, {
closeButton: true,
})
});
Toaster is basically just a div at the top of your screen that disappears after a while. You can build your own solution. Toaster and other projects like it are just commonly used for this purpose.
If you want a custom drop-down component with all the notifications then you have to build it and style it like any other component. When the component is in place, save the messages to firebase/firestore database inside the .onMessage snippet above and then retrieve the message inside your new notifications component.