I have set up a test project in order to test Firebase with unity webGL builds.
I have created a *.jslib plugin to keep my js functions in there :
mergeInto(LibraryManager.library, {
GetJSON: function (path, objectName, callback, fallback) {
var parsedPath = Pointer_stringify(path);
var parsedObjectName= Pointer_stringify(objectName);
var parsedCallback = Pointer_stringify(callback);
var parsedFallback = Pointer_stringify(fallback);
try{
firebase.database().ref(parsedPath).once('value').then(function(snapshot) {
window.unityInstance.SendMessage(parsedObjectName, parsedCallback , JSON.stringify(snapshot.val()));
});
} catch(error){
window.unityInstance.SendMessage(parsedObjectName, parsedFallback, "There was an error: " + error.message);
}
}
});
After building and running, I add my Firebase config snippet into the index.html file(I have hidden the actual keys on this snippet):
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-analytics.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "key",
authDomain: "domain",
projectId: "id",
storageBucket: "bucket",
messagingSenderId: "senderID",
appId: "appId",
measurementId: "measurementId"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>
In unity, I am testing this by calling the GetJSON function, and I have a callback, and a fallback method:
void Start()
{
text.text = "Start worked";
GetJSON(path: "example", gameObject.name, callback: "OnRequestSuccess", fallback: "OnRequestFailed");
}
public void OnRequestSuccess(string data)
{
text.color = Color.green;
text.text = data;
}
public void OnRequestFailed(string error)
{
text.color = Color.red;
text.text = error;
}
After I have built and run my webGL project, and updated the index.html file with the proper configurations, the text turns red (Which means the OnRequestFailed() was called) and it says: "There was an error: firebase is not defined". Which means, it does not recognize the firebase when I use it on the *.jslib plugin. Where should the firebase be defined exactly? Because I am defining it in my index.html, or at least I think so?
Related
I made a Firebase app with database, connected it with Vue app, which is like todo-list. I tried to get a data from database from firebase, which is used to make components for app, but something got wrong. Vue app doesn't get the data from firebase, so items aren't created
It's th error:
#firebase/firestore: Firestore (9.10.0): Uncaught Error in snapshot listener: {"code":"permission-denied","name":"FirebaseError"
Initializing firebase:
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
import { getFirestore } from "#firebase/firestore";
const firebaseConfig = {
apiKey: "AIzaSyBZlP_E74i40ZLopttFlUbg3j36wirKf9A",
authDomain: "quotes-app-8788c.firebaseapp.com",
projectId: "quotes-app-8788c",
storageBucket: "quotes-app-8788c.appspot.com",
messagingSenderId: "934346412075",
appId: "1:934346412075:web:5da2928fecb05c834f5a6e"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export {
db
}
Here is my code:
onSnapshot(collection(db, 'quotes'), (QuerySnapshot) => {
const fbquotes = [];
QuerySnapshot.forEach((doc) => {
const quote = {
id: doc.data().id,
quoteText: doc.data().quoteText,
quoteAuthor: doc.data().quoteAuthor,
quoteGenre: doc.data().quoteGenre,
timeCreating: doc.data().timeCreating,
timeEditing: doc.data().timeEditing
}
this.fbquotes.push(quote)
})
this.quotes = fbquotes
console.log(this.quotes);
})
console.log(this.quotes);
},
The error code "permission-denied" tells that your security rules are not allowing the user to query that whole collection. If a user can read all documents from the "quotes" collection then make sure you have the following rules:
match /quotes/{quotesId} {
allow read: if true;
}
You can change the condition for allow read if your requirements are different. Also Security Rules are not filters so if you want to allow a user to read their own documents only, then make sure you change the query in your code as well to match the security rules.
Having devoted many hours to search the internet for a simple and straightforward way of how to implement Firebase FCM Push Notification on my nuxt project bore no fruit.
Here is how to implement FCM Push Notifications on your NuxtJs/Vuejs project
Step 1
Create your nuxt app like npx create-nuxt-app <your-app-name>
Step 2
Install firebase npm install firebase and #nuxt/firebase npm install #nuxt/firebase
Step 3
Creating your firebase project
Go to firebase console and create a project
Give it a name
Enable Google analytics if you like to then click on create
-Get some coffee as the projects creates ☕
On this page you want to copy the config, which we will use later
Finally, we land on the home page of our project on firebase, looks like below image
Let's go back to our project
Step 4
On your nuxt.config.js add
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
'#nuxtjs/firebase',
],
// firebase FCM starts here
firebase: {
lazy: false,
config: {
apiKey: <apiKey>,
authDomain: <authDomain>,
projected: <projectId>,
storageBucket: <storageBucket>,
messagingSenderId: <messagingSenderId>,
appId: <appId>,
measurementId: <measurementId>,
databaseURL: <databaseURL>,
},
onFirebaseHosting: false,
services: {
messaging: true,
}
},
messaging: {
createServiceWorker: true,
actions: [
{
action: 'goHome',
url: 'https://localhost:3000'
}
],
fcmPublicVapidKey: <vapidKey>
},
To get your vapidKey navigate to Project Settings on your firebase console and select Cloud Messaging, scroll down and press on Generate Key Pair to have your vapidKey.See image below
copy and paste it on your nuxt.config.js
Step 5
On the static folder at your project root create a file named firebase-messaging-sw.js and paste the input the configs as below
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing the generated config
var firebaseConfig = {
apiKey: <apiKey>,
authDomain: <authDomain>,
projected: <projectId>,
storageBucket: <storageBucket>,
messagingSenderId: <messagingSenderId>,
appId: <appId>,
measurementId: <measurementId>,
databaseURL: <databaseURL>,
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
Step 6
On your index.vue configure it as follows
<template>
<div>
<h1>Get Notified</h1>
</div>
</template>
<script>
export default {
data() {
return {
listenersStarted: false,
idToken: "",
};
},
mounted() {
this.startListeners();
},
methods: {
// FCM NOTIFICATION FUNCTIONS
async startListeners() {
await this.startOnMessageListener();
await this.startTokenRefreshListener();
await this.requestPermission();
await this.getIdToken();
this.listenersStarted = true;
},
startOnMessageListener() {
try {
this.$fire.messaging.onMessage((payload) => {
console.info("Message received : ", payload);
console.log(payload.notification.body);
});
} catch (e) {
console.error("Error : ", e);
}
},
startTokenRefreshListener() {
try {
this.$fire.messaging.onTokenRefresh(async () => {
try {
await this.$fire.messaging.getToken();
} catch (e) {
console.error("Error : ", e);
}
});
} catch (e) {
console.error("Error : ", e);
}
},
async requestPermission() {
try {
const permission = await Notification.requestPermission();
console.log("GIVEN notify perms");
console.log(permission);
} catch (e) {
console.error("Error : ", e);
}
},
async getIdToken() {
try {
this.idToken = await this.$fire.messaging.getToken();
console.log("TOKEN ID FOR this browser");
console.log(this.idToken);
} catch (e) {
console.error("Error : ", e);
}
},
},
};
</script>
Step 7
Run npm run dev , open your console to see if the permissions to display notifications are granted. Accept if promoted to allow notifications.
Step 8
Navigate to Cloud Messaging on firebase Engage menu and click on Send your first message. Type the content you would like your notification to have and select your app as the target user, there we have it you should see a notification on your browser like so
I am trying to access my realtime database in firebase but it shows me this error Uncaught Error: Service database is not available. I have searched for what this could posabbly mean but I couldn't find anything useful or a solution.
Here is my code:
window.addPerson = addPerson;
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const userVar = urlParams.get('user')
const userVarSplitted = userVar.split('#')
const userVarFormatted = userVarSplitted[0] + ":" + userVarSplitted[1]
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-analytics.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-database.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {MY FIREBASE CONFIG};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
if (app.length === 0) {
console.log("no firebas app")
}else{
console.log("initialized")
}
const analytics = getAnalytics(app);
const database = getDatabase(app);
function addPerson() {
set(ref(database, "verified/" + userVarFormatted), {
name: userVarSplitted[0],
discriminator: userVarSplitted[1]
});
console.log("added")
PS: The script type is set to modular.
Do you know what the error means and what is happening?
You're using difference versions of the Firebase SDKs. I'd update the database import to version 9.6.4 too, so that the all Firebase SDK versions are the same.
I am pretty new to expo and firebase, and I have this error that I have no idea what the issue is. I am trying to fetch photos from firebase database. I know for sure the issue is not with firebase config because I can upload photos into firebase storage.
I suspect the issue is with exporting and importing firebase.
This is the error message I am getting :
[TypeError: _firebase.db.ref is not a function. (In
'_firebase.db.ref('users/photos')', '_firebase.db.ref' is undefined)]
Note: I am using firebase v9
App.js file:
import { db } from './firebase';
export default function App() {
async function loadPhotos() {
try {
db.ref('users/photos')
.then(url => {
console.log('URL: ', url);
})
.catch(e => console.log(e));
console.log('Got here');
} catch (error) {
console.log('error', error);
}
}
...............
}
firebase.js file:
import firebase from 'firebase/compat/app';
import { getDatabase } from 'firebase/database';
const firebaseConfig = {
apiKey: '......',
authDomain: '.....',
projectId: '....',
storageBucket: '....',
messagingSenderId: '....',
appId: '.....',
measurementId: '....',
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export const db = getDatabase();
In v9 and later of the Firebase SDK, most functionality that was a method on the objects in the past, is now available as a top-level function.
So instead of db.ref('users/photos'), you need to do ref(db, 'users/photos').
You're also missing a get call, which is how you actually retrieve the data from the reference:
get(ref(db, 'users/photos'))
.then(url => {
console.log('URL: ', url);
})
.catch(e => console.log(e));
This is all pretty well documented in the Firebase documentation on reading data, so I recommend keeping that handy. Alternatively you can use the compat paths in v9, to make the older syntax work as shown in the upgrade guide/
I want to reload or trigger some event in foregrounf if push message is sent with firebase.messaging().onMessage, but it not fired. I'm using firebase.mesaging.sw.js with background notification and it works correctly what is wrong with my code?
firebase.js
const config = {
apiKey: "x",
projectId: "x",
storageBucket: "x",
messagingSenderId: "x"
};
firebase.initializeApp(config);
const msg = firebase.messaging()
msg.requestPermission()
.then(() => {
return msg.getToken()
})
.then((token) => {
})
.catch((err) => {
})
msg.onMessage(function(payload) {
alert("Foreground message fired!")
console.log(payload)
});
firebase.messaging.sw.js
importScripts("https://www.gstatic.com/firebasejs/7.0.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.0.0/firebase-messaging.js");
const config = {
apiKey: "x",
projectId: "x",
storageBucket: 'x',
messagingSenderId: "x"
};
firebase.initializeApp(config);
const msg = firebase.messaging()
msg.setBackgroundMessageHandler(function(payload) {
let options = {
body: payload.data.body,
icon: payload.data.icon
}
return self.registration.showNotification(payload.data.title, options);
});
I don't know what is wrong with my code
Simple solution to this is update your Firebse to latest version.
Eg.
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
Note: Once you have updated your firebase libraries versions then messagingSenderId will not work in your firebase-messaging-sw.js file. You have to provide all other params eg. apiKey, projectId, appId along with messagingSenderId.
If still not work. Clean your browser cache and re-register service worker.
For more details you can refer to this solution
Still had the same issue in 2020. In my case it was like this:
you need to have same versions in importScripts for background messages and in your app for foreground messages
call it after obtaining token for background service
firebaseApp.messaging().getToken().then((currentToken) => {
if (currentToken) {
console.log(currentToken)
} else {
// Show permission request.
console.log(
'No Instance ID token available. Request permission to generate one.')
}
/** When app is active */
firebase.messaging().onMessage((payload) => {
console.log(payload)
}, e => {
console.log(e)
})
})
For anyone else with this problem, I finally solved it by:
Upgrading the Firebase SDK version in both header-included JS files and the SW JS file to latest (currently, that would be 7.8.1).
Adding the entire firebaseConfig array to the SW firebase.initializeApp(), as the previous answer suggests.
Cleaning the Chrome cache from the Application > Clear Storage section in the Developer Tools.
Deleting the previous registration token from my database.
Blocking and unblocking notifications from the browser to force a new token generation.
Basically, a total fresh start with updated Firebase SDK seems to fix issues like this.
You are missing lots of things and onMessage will only work if firebase is initialized before calling it. Please follow this. I have done it like this and it is working.
initialize firebase and get the token
export class BrowserFcmProvider {
export const FIREBASE_CONFIG = {
apiKey: "****",
authDomain: "****",
databaseURL: "****",
projectId: "****",
storageBucket: "****",
messagingSenderId: "****",
appId: "****"
}
firebase.initializeApp(FIREBASE_CONFIG);
async webGetToken() {
try {
const messaging = firebase.messaging();
await messaging.requestPermission();
const token = await messaging.getToken();
let uuidTemp = new DeviceUUID().get();
return this.saveTokenToFireStoreFromWeb(token, uuidTemp)
} catch (e) {
console.log(e);
}
}
saveTokenToFireStoreFromWeb(token, uuid) {
try {
const docData = {
token: token,
device_type: 'web',
uuid: uuid
}
const devicesRef = this.db.collection('devices')
return devicesRef.doc(uuid).set(docData);
} catch (e) {
console.log(e, 'saveTokenError');
}
}
showMessage() {
try {
const messaging = firebase.messaging();
messaging.onMessage((payload) => {
console.log(payload);
})
} catch (e) {
console.log(e)
}
}
}
And calling the method while app loads like this
async configureFirebaseForBrowser(res) {
await this.bfcm.webGetToken();
this.bfcm.showMessage();
}
Firebase function and payload type
const payloadWeb = {
title: title,
body: body,
data: {
title: title,
body: body
},
tokens: uniqueDevicesTokenArrayWeb,
}
const responseWeb = await admin.messaging().sendMulticast(payloadWeb);
console.log(responseWeb.successCount + ' notifications has been sent to Web successfully');
I have used async and await as we need to manage firebase/firestore operations asynchronously.
fcm does not work in Incognito mode and safari browser
Same issue i was faced. In my case firebase version in "package.json" and "firebase-messaging-sw.js" importScripts version was different. After set same version in "firebase-messaging-sw.js" importScripts which was in
"package.json", my issue is resolved.
Before change
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
After change
**"package.json"**
"firebase": "^8.2.1",
**"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');