Browser push notifications only on logged in | Firebase - javascript

I was implementing Firebase Browser push notifications in a React Project,
But I want the browser push notifications to come only when the user is logged in to the my website or application.
My requirement is:
Send Browser notifications to the user who are signed in, with their name, and some other details.
For the users not signed in, a generic message should go to them.
My service-worker file and the push-notifications file is as follows:
push-notifications.js
import firebase from 'firebase';
export const initializeFirebase = () => {
firebase.initializeApp({
apiKey: "xxx",
authDomain: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx"
});
const messaging = firebase.messaging();
messaging.onMessage((payload) => {
console.log("Loading...",payload);
alert("Firebase is awesome");
});
}
export const askForPermissioToReceiveNotifications = async () => {
try {
const messaging = firebase.messaging();
await messaging.requestPermission();
const token = await messaging.getToken();
console.log('token: ', token);
return token;
} catch (error) {
console.error(error);
}
}
export const getMessagingToken = async () => {
try {
const messaging = firebase.messaging();
const token = await messaging.getToken({vapidKey:
"xxx"});
return token;
} catch (error) {
console.error(error);
}
}
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
firebase.initializeApp({
apiKey: "xxx",
authDomain: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx"
});
const messaging = firebase.messaging();
console.log(messaging);
Everything is working fine, but I want to send the notifications only to the users that have currently logged in to the website.
And some notifications to the users that are not logged in to the application.
I am not able to find any resource on firebase offical site for the same.
It would be great help if you share any relevant resources or answer the way to complete the requirement.
Thanks in advance!
Feel free to ask in case of any queries.

Related

TypeError: _app.default.auth is not a function - React Native Web - Firebase

I am currently developing a project on React Native Web and this is my login call in a component. (The call is in the components useEffect, as soon as the component opens, it should log in anonymously)
import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
const firebaseConfig = {
apiKey: "****",
authDomain: "****",
projectId: "****",
storageBucket: "****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
};
firebase.initializeApp(firebaseConfig)
const login = async () => {
firebase.auth().signInAnonymously()
.then((userCredential) => {
// Signed in
// ...
})
.catch((error) => {
console.log("LOG: "+error)
});
}
But everytime I get the error: Uncaught (in promise) TypeError: _app.default.auth is not a function
I tried several different imports, but none of them seemed to work.
I see the error when I open the Console on Firefox. How can I fix this issue?
Thanks
Try this approach by checking if firebase is initialized and the user is not logged in:
const [loggedIn, setLoggedIn] = React.useState(false)
React.useEffect(() => {
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: "****",
authDomain: "****",
projectId: "****",
storageBucket: "****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
});
}
}, [])
React.useEffect(() => {
if (firebase.apps.length && !loggedIn) {
setLoggedIn(true)
login()
}
}, [firebase])
const login = async () => {
firebase.auth().signInAnonymously()
.then((userCredential) => {
// Signed in
// ...
})
.catch((error) => {
console.log("LOG: " + error)
});
}

Firebase - Failed to get document because the client is offline (v9 Upgrade)

Recently upgraded to firebase v9 from v8 in my React Native project and I am now unable to use my legacy v8 firestore methods.
The error I am receiving is:
[Unhandled promise rejection: FirebaseError: Failed to get document because the
client is offline.]
I initialize firebase in a file I call fire-config.js. The commented //import firebase from 'firebase'; is how I previously imported firebase in v8.
I then would import fire from fire-config.js into my controller methods. Ex: userController.js.
I tried a couple different combinations of /compat and /compat/app to no avail. I was following the upgrade guide (https://firebase.google.com/docs/web/modular-upgrade) which my understanding was update the path and that was all that was needed.
Package.json:
"firebase": "9.0.2",
fire-config.js
//import firebase from 'firebase';
import firebase from 'firebase/compat';
require("firebase/functions");
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "XXXXX",
authDomain: "XXXXX",
databaseURL: "XXXX",
projectId: "XXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXXX",
appId: "XXXX",
measurementId: "XXXXX"
};
try {
firebase.initializeApp(firebaseConfig);
} catch(err){
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)}
}
const fire = firebase;
export {fire};
userController.js
import {fire} from "../config/fire-config";
const getUserDetail = async (user) => {
let userDetail = {};
await fire
.firestore()
.collection("users")
.doc(user.uid)
.get()
.then((doc) => {
if (doc.exists) {
userDetail = {
id: doc.id,
...doc.data(),
};
}
});
return userDetail;
};

Firebase web push notification sent successfully but not received by the client

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

FCM Web send message succeeds but nothing appears in Browser

I am sending following Notification
Authorization:key=A.....
Content-Type:application/json
{
"to" : "cBx_ErhkhNw:APA91bEzwHvZ2daEK15Y3A0VAprxPV-4GGq10FjlrFnHzCs8xSJXz2lATjh9AoLRQvnSseT6r4ggApC6TbtD9M_sI_BDDmycZ1TEVn0HaF5pAABeSbHqcOK-kmkPqOve1VThUaUIXQy4",
"notification": {
"title": "Test Nachricht",
"body": "This is a message from FCM to web"
},
"priority": "high",
"webpush": {
"fcm_options": {
"link": "https://dummypage.com"
}
}
}
And have following code:
app.js
// Initialize Firebase
var config = {
apiKey: "<KEY>",
authDomain: "<AUTH_DOMAIN>",
databaseURL: "<DB_URL>",
projectId: "atlas-test-35d33",
storageBucket: "<STORAGE_BUCKET>",
messagingSenderId: "817272374311"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.usePublicVapidKey("<PUBLIC_KEY>");
messaging.requestPermission()
.then(function() {
console.log("Permission granted");
return messaging.getToken()
})
.then(function(token) {
console.log(token)
})
.catch(function(err) {
console.log(err)
})
console.log("listenting")
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
// ...
});
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/5.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.9.0/firebase-messaging.js');
var config = {
apiKey: "<KEY>",
authDomain: "<AUTH_DOMAIN>",
databaseURL: "https://atlas-test-35d33.firebaseio.com",
projectId: "atlas-test-35d33",
storageBucket: "<STORAGE_BUCKET>",
messagingSenderId: "817272374311"
};
firebase.initializeApp(config);
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
When I try to send a Notification to the fcm Server I get following response:
{
"multicast_id": 5394725759940263108,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1552646324437940%e609af1cf9fd7ecd"
}
]
}
Which seems, like everything is fine for me. But I dont receive anything in my Web application. I just hardcoded the "to" token for testing purposes but I dont think thats the Problem.
Do you have any clue whats the problem, or is there any debug possibility.
Thanks!

How can I create FCM token for web application?

I want to create FCM token for web application based on this i want to send push notifications.Is it possible?Can i expect sample code for this?
I try this one
var config = {
apiKey: "AIzaSyC2GoeeoYfPTgP61w77FMPFep-cLBz9Pmc",
authDomain: "sample-3a7a1.firebaseapp.com",
databaseURL: "https://sample-3a7a1.firebaseio.com",
projectId: "sample-3a7a1",
storageBucket: "sample-3a7a1.appspot.com",
messagingSenderId: "990467369229"
};
firebase.initializeApp(config);
const messaging=firebase.messaging();
messaging.requestPermission()
.then(function(){
console.log('Have permission');
return messaging.getToken();
})
.then(function(token){
console.log(token);
})
but it shows following error
Uncaught e {code: "app/no-app", message: "Firebase: No Firebase App '[DEFAULT]' has been cre…- call Firebase App.initializeApp() (app/no-app).", name: "[DEFAULT]", stack: "FirebaseError: Firebase: No Firebase App '[DEFAULT… at http://localhost:8080/FCMPushNotify/:88:30"}

Categories

Resources