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.
Related
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);
});
I am developing a chrome extension. I want to send FCM messages to extension via Firebase from external server by specific token, but I can't receive this token.
I try to receive token in background script by call the following code:
async function registerFirebaseApp(): Promise<void> {
if (!navigator && !('serviceWorker' in navigator)) {
return;
}
try {
firebase.initializeApp({
apiKey: "AIzaSyAMhLAPjiAjUUdoxXLaJtgHlEC9WB8wWZY",
authDomain: "berrywallet-spreader.firebaseapp.com",
databaseURL: "https://berrywallet-spreader.firebaseio.com",
projectId: "berrywallet-spreader",
storageBucket: "berrywallet-spreader.appspot.com",
messagingSenderId: "508872957744",
});
console.log('1');
const messaging = firebase.messaging();
console.log('2');
// This promise never resolves. No result. No error.
const currentToken: string = await messaging.getToken();
console.log('3');
console.log('Push token!', currentToken);
} catch (error) {
console.error(error);
}
}
Then I have console log
1
2
... it's all.
I expect to catch at least an exception, but not.
File with code which tring to get token in repository: Background/application.ts
Firebase message SW: firebase-messaging-sw.js
Well, simply put, I cannot receive messages via my WebApp using JS. I am receiving tokens and I am able to send messages via Firebase console to the WebApp's token, but I am not getting any receiving.
Here is my JS Code:
var config = {
apiKey: "AIzaSyBLCsBQVXLsDjPhjdkvJVMGyDUcfWrFtQU",
authDomain: "php-test-project-78c66.firebaseapp.com",
databaseURL: "https://php-test-project-78c66.firebaseio.com",
projectId: "php-test-project-78c66",
storageBucket: "php-test-project-78c66.appspot.com",
messagingSenderId: "856365479454"
};
firebase.initializeApp(config);
$(document).ready(function(){
const messaging = firebase.messaging();
messaging.requestPermission().then(function() {
console.log("Permitted");
return messaging.getToken();
}).then(function(token) {
console.log(token);
}).catch(function(error) {
console.log("Not Permitted");
});
messaging.onMessage(function(payload) {
console.log("TEST");
console.log("Message received. ", payload);
});
});
Upon sending message via Firebase Console, I do not receive anything. I send by using TokenID.
PS: The keys are of a Dev Testing App, hence I kept it in. If admins consider this a problem then you may remove it.
So I follow this firebase tutorial and seemingly to I do everything according to the documentation but I still get errors. Youtube FCM Tutorial
var config = {
apiKey: "AIzaSyAyWVXB9KFLm2ymoBoiY-TothNYgo3IrtA",
authDomain: "fir-end-cff84.firebaseapp.com",
databaseURL: "https://fir-end-cff84.firebaseio.com",
projectId: "fir-end-cff84",
storageBucket: "fir-end-cff84.appspot.com",
messagingSenderId: "297653223714"
};
firebase.initializeApp(config);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./firebase-messaging-sw.js').then(function (registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
console.log('Have Permit');
return messaging.getToken();
})
.then(function (token) {
console.log(token);
})
.catch(function (err) {
console.log(err);
})
These are the logs:
And this is the project overview:
Im using the latest version of webstorm on ubuntu 16.04
Edit: I even used this repo but still have the same issue
https://github.com/firebase/quickstart-js/tree/master/messaging
Apperently to get the fcm token your localhost needs to have application server capabilities, some webstorm's localhost wont do!
I am trying to implement Firebase Cloud Messaging (FCM) for push notifications into my web application (AngularJS). For this I have created one firebase-messaging-sw.js in the root app folder.
// firebase-messaging-sw.js
'use strict';
console.log('Starting service worker');
if ('function' === typeof importScripts) {
importScripts('https://www.gstatic.com/firebasejs/3.5.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.5.0/firebase-messaging.js');
// importScripts('core/decoder.js');
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
'messagingSenderId': '1043000236721'
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
var messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
var shinyData = payload || {};
var title = 'New Notification';
console.log('[firebase-messaging-sw.js] Received background message ', payload, shinyData);
return self.registration.showNotification(title, {
body: shinyData.body,
icon: '/resources/images/web-logo.png',
data: { url: '/#!/home' }
});
});
self.addEventListener("notificationclick", function (event) {
var urlToRedirect = event.notification.data.url;
event.notification.close();
event.waitUntil(self.clients.openWindow(urlToRedirect));
});
}
and one manifest.json file containing the gcm-sender-id as follows:
{
"manifest_version": 2,
"name": "My Extension",
"version": "versionString",
"default_locale": "en",
"description": "A plain text description",
"gcm_sender_id": "103953800517"
}
In the index.html I have initialized Firebase as follows:
<script>
var config = {
apiKey: "API-key",
authDomain: "some-authdomain",
databaseURL: "firebase-databaseUrl",
storageBucket: "storage-bucketUrl",
messagingSenderId: "senderId"
};
firebase.initializeApp(config);
</script>
With all these configuration the FCM push notifications are working fine. But the problem is coming when we logout. At the time of logout I am unregistering the service worker as follows:
navigator.serviceWorker.getRegistrations().then(function (registrations) {
angular.forEach(registrations, function (registration) {
registration.unregister();
});
});
Now, when I try to login again then push notification doesn't works as
after unregistering all the service worker , I am unable to
reinitialise the firebase app. If I reload the page after logout then
the FCM works perfectly fine as on reload firebase-messaging-sw.js is
loaded again and setup the service worker again.
Please help me to provide the solution for proper logout and login for enabling smooth functioning of FCM.
I haven't really tried this solution but I believe this should work.
Write this code in a function as:
async function init() {
const registration = await navigator.serviceWorker.register('/firebase-messaging-sw.js');
await navigator.serviceWorker.ready;
var config = {
apiKey: "API-key",
authDomain: "some-authdomain",
databaseURL: "firebase-databaseUrl",
storageBucket: "storage-bucketUrl",
messagingSenderId: "senderId"
};
firebase.initializeApp(config);
// getToken and all stuffs
}
And call the function init() as soon as the user login.
Also, whenever the user logout, you should unregister the service worker with
navigator.serviceWorker.getRegistrations().then(function (registrations) {
angular.forEach(registrations, function (registration) {
registration.unregister();
});
});
Hope this works for you.