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.
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'm using firebase web push notifications API and sending post request with the message I want to display on the client-side with Postman and/or from the firebase notifications composer, the message is being sent successfully but it is not being received, how can I fix this?
This is the response I get
{
"multicast_id": 6360733777037549929,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1592759038463623%cc9b4facf9fd7ecd"
}
]
}
I'm using Firebase hosting, and including the entire Firebase Javascript SDK, although I already tried including only firebase-messaging SDK.
<body>
<h1>Some Firebase app</h1>
<script src="/__/firebase/7.15.3/firebase.js"></script>
<script src="/__/firebase/init.js"></script>
<script type="text/javascript">
const messaging = firebase.messaging();
messaging.requestPermission()
.then(()=>{
console.log('Permission Granted');
return messaging.getToken()
})
.then((token)=>{
console.log(token);
})
.catch((err)=>{
console.log(err);
})
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
</script>
</body>
With the token I get, and with my server key I send the following request
Method: POST
URL: https://fcm.googleapis.com/fcm/send
Headers: {
Authorization: "key=myServerKey",
Content-Type: "application/json"
}
Body: {
"to" : "token",
"notification" : {
"body" : "Test message",
"title" : "Test title"
}
}
And this is how I handle the message on firebase-messaging-sw.js file
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "newproject-95acc.firebaseapp.com",
databaseURL: "https://newproject-95acc.firebaseio.com",
projectId: "newproject-95acc",
storageBucket: "newproject-95acc.appspot.com",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.initializeApp(firebaseConfig);
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
Which you want to receive message in the Foreground(has focus), or in the Background (service worker)?
in the Background (service worker)
Could you try the following code?
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "newproject-95acc.firebaseapp.com",
databaseURL: "https://newproject-95acc.firebaseio.com",
projectId: "newproject-95acc",
storageBucket: "newproject-95acc.appspot.com",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.initializeApp(firebaseConfig);
if (firebase.messaging.isSupported()) {
firebase.messaging();
}
See https://firebase.google.com/docs/cloud-messaging/js/receive
If you set notification fields in your message payload, your setBackgroundMessageHandler callback is not called, and instead the SDK displays a notification based on your payload.
Or, Could you try samples?
See:
https://github.com/firebase/functions-samples/tree/master/fcm-notifications
https://github.com/firebase/functions-samples/blob/master/fcm-notifications/public/main.js
https://github.com/firebase/functions-samples/blob/master/fcm-notifications/public/firebase-messaging-sw.js
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
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
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.