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!
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 using Vue js on client-side and node js on the backend side. I am sending data message and it is getting received by the client-side when the browser's tab is inactive. But when the tab is active, it doesn't receive notification.
Here is my code on client-side
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "<apiKey>",
authDomain: "<authDomain>",
databaseURL: "<db>",
projectId: "<projectId>",
storageBucket: "<storageBucket>",
messagingSenderId: "<senderId>",
appId: "<appId>"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
messaging.usePublicVapidKey(
"<KEY>"
);
messaging
.requestPermission()
.then(function() {
retrieveToken();
console.log("Notification permission granted.");
})
.catch(function(err) {
console.log("Unable to get permission to notify. ", err);
});
function retrieveToken() {
messaging
.getToken()
.then(deviceToken => {
if (deviceToken) {
console.log(deviceToken);
messaging.onMessage(payload => {
console.log("Message received. ", payload);
});
} else {
console.log(
"No Instance ID token available. Request permission to generate one."
);
}
})
.catch(err => {
console.log("An error occurred while retrieving token. ", err);
});
}
}
</script>
And here is my server side code
var message = {
data: {
score: "850",
time: "2:45"
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin
.messaging()
.send(message)
.then(response => {
// Response is a message ID string.
console.log("Successfully sent message:", response);
})
.catch(error => {
console.log("Error sending message:", error);
});
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
I am trying to send the notification to the specific user using firebase. Going on with tutorials, I could not solve this in the beginning phase.
Here is my js:
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.usePublicVapidKey("");
messaging.requestPermission().then(function() {
console.log('Notification permission granted.');
return messaging.getToken();
}).then(function(token){
console.log(token);
})
function getRegToken(){
messaging.getToken().then(function(currentToken) {
if (currentToken) {
// sendTokenToServer(currentToken);
console.log(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
setTokenSentToServer(false);
}
}).catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
}
I have inserted correct parameters inside the config and public key
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.