How can I create FCM token for web application? - javascript

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"}

Related

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;
};

Browser push notifications only on logged in | Firebase

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.

Flutter Web: FCM cannot register Service Worker

I am trying to implement FCM notification inside a Flutter Web application but I am getting errors when registering my service worker. I think it might come from the way my files index.html and firebase-messaging-sw.js are made.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MyApp</title>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var devConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DB_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize Firebase
firebase.initializeApp(devConfig);
</script>
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
navigator.serviceWorker.register("/firebase-messaging-sw.js");
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.5.0/firebase-messaging.js');
var devConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DB_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
// 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(devConfig);
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
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);
});
Errors
Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
at p (https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js:1:10100)
at Object.o [as messaging] (https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js:1:9710)
at http://localhost:56234/firebase-messaging-sw.js:33:28
Uncaught (in promise) TypeError: Failed to register a ServiceWorker for scope ('http://localhost:56234/') with script ('http://localhost:56234/firebase-messaging-sw.js'): ServiceWorker script evaluation failed
I am testing the application using the command flutter run -d web-server.
I am correctly calling await Firebase.initializeApp() before starting my application in my main.dart.
I am using the package firebase_core: ^0.5.0.
I have tested with firebase scripts in version 7.22.1 and 7.5.0.
add follow ing in your index.html
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-messaging.js"></script>

Firebase data retrieval to web

// Initialize Firebase
var config = {
apiKey: "AIzaSyBz13eirmEOGD1uXOZwf6tKGnEsjfwsUFo",
authDomain: "platformtechproject.firebaseapp.com",
databaseURL: "https://platformtechproject.firebaseio.com",
projectId: "platformtechproject",
storageBucket: "platformtechproject.appspot.com",
messagingSenderId: "1065758005439"
};
firebase.initializeApp(config);
var database = firebase.database();
ref msgs clllection
var msgRef = firebase.database().ref('survey');
I am trying to connect to firebase, but I continue getting these errors on chrome console failing to connect to firebase:
Chrome console error
This is because you did not write:
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
in the <head>...</head>
You have to write it to be able to use the firebase sdk in your project.
more info here:
https://firebase.google.com/docs/web/setup

FCM Cannot receive messages on WebApp

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.

Categories

Resources