Firebase onMessage() not receiving messages - firebase

I'm developing a Firebase real-time messaging app. I've successfully managed to upload the browser/device token into the collection in the Firestore, but when I'm trying to test if the messages are being received in the app, I'm not getting any.
Here are some parts of my code.
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-functions.js"></script>
<script>
var firebaseConfig = {
---- PRIVATE ----
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<script src="firebase-messaging-sw.js?v=2156"></script>
Already tried writing the necessary code for the firebase-messaging-sw (https://stackoverflow.com/a/50078103/3881610) but I'm getting an error saying:
Uncaught FirebaseError: Messaging: This method is available in a service worker context. (messaging/only-available-in-sw).
I also have the code to receive messages in the page:
var messaging = firebase.messaging();
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
Also made sure that messages are being SENT to the device token using Postman and works just fine.
Any thoughts? Thanks!

At first, firebase-messaging-sw.js is service worker JavaScript file.
See Firebase messaging importScripts is not defined
And could you try samples?
See:
https://github.com/firebase/quickstart-js/tree/master/messaging
https://github.com/firebase/functions-samples/tree/master/fcm-notifications

Related

Module not found in nextJs when using slack web API

I'm building a next.js application that uses the slack web API to fetch a list of channels once user is authenticated.
Unfortunately, I'm getting the following error:
Module not found: Can't resolve 'fs'
Now, this only happens after I start using the slack client within my app:
const getChannels = async (token: string) => {
const result = await slackClient.channels.list({
token,
});
return result;
};
use(getChannels(session?.authToken));
I saw a couple of posts on SO mentioning the fs error within next.js apps, but they were all related to middleware, while I'm not using any.
Why would I need to access fs? Do I have to create a custom middleware?

How to listen for realtime updates in Firebase Cloud Firestore?

In the official documentation of Firebase, we can do it with https://firebase.google.com/docs/firestore/query-data/listen
let doc = db.collection('cities').doc('SF');
let observer = doc.onSnapshot(docSnapshot => {
console.log(`Received doc snapshot: ${docSnapshot}`);
// ...
}, err => {
console.log(`Encountered error: ${err}`);
});
But how can we do it with Google Apps Script?
To run an Apps Script on a event (like a data update) implies using triggers. Unfortunately, at the moment there are no Apps Script triggers supporting Firebase.
However, you can include JavaScript code in the HTML file attached to your Apps Script file and deploy it as a Web App.

How to import firebase into google apps script, in order to create users with google provider?

I'm trying to create a new user in firebase via the google auth provider either automatically or by the click of a button in a sidebar addon in google sheets. The reason being is I need to get a registered uid for the user so the data that I send from sheets can be attributed to this user.
The closest thing I've found to a tutorial is this, but I get stuck when trying to import firebase.
One method I'm seeing a lot is importing it via a script tag in the html for the sheets side bar.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
// Initialize Firebase
var config = {
apiKey: '...,
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '...'
};
firebase.initializeApp(config);
</script>
</body>
</html>
However when I try to use the firebase variable in my .gs script it is undefined. How would I make it available to the script?
The other method I've seen is using eval and URLFetchApp in the gs script.
eval(UrlFetchApp.fetch("https://www.gstatic.com/firebasejs/5.9.2/firebase.js").getContentText());
This results in SyntaxError: Missing name after . operator.
I think this is because this library isn't intended to run on node js.
I realize that the admin sdk for firebase is intended for node js but you can't create a user with a specific provider with this method (afaik). Also I'm not sure how I would import it to Google apps script anyways. Additionally I want the user to interact with the google account selector after initiating the create user process.
Does anyone have any suggestions as to how to get this done?
It is actually quite easy to create new users in Firebase from a Google Sheet by using the Firebase Auth REST API.
You have to issue an HTTP POST request to the Auth signupNewUser endpoint, see the detailed doc here: https://firebase.google.com/docs/reference/rest/auth/#section-create-email-password
For that you will use the fetch() method of the URLFetchApp() Class in your gs script, as follows:
function createUser() {
const userName = "john.doe#gmail.com";
const pwd = "xyz987";
const createUserUrl = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=[API_KEY]" //Replace with your Web API Key
const payload = JSON.stringify({"email": userName, "password": pwd, "returnSecureToken": true});
const createUserResponse = UrlFetchApp.fetch(createUserUrl, {
method: 'post',
contentType: 'application/json',
muteHttpExceptions: true,
payload : payload
});
Logger.log(JSON.parse(createUserResponse));
}
You will obtain the Web API Key for your Firebase project through the project settings page in your Firebase admin console.

Firebase Cloud Messaging for web: how to send to multiple tokens?

i hope i don't get downvotes on this one, i've been trying to set up web notifications for my CMS using Firebase, and i noticed that Google's Firebase documentations on the topic are huge, i mean very huge you get confused.
So far i managed to add the functionality of letting people subscribe to the notification by letting the browser asking their permission to send them notifications, then i get the unique tokens after they accept and store those tokens in my database, i also managed to change the location of the service worker and everything looks good and dandy.
Now, i want to send a notification to all my users (tokens) that are stored in my database, i think looping through them and send a notification using CURL to each one individually is a nasty solution. I can't find a documentation on how to send a notification to all my tokens in one CURL call.
This is my code so far:
<!-- Firebase Technologies -->
<!-- Firebase App is always required and must be first -->
<script src="https://www.gstatic.com/firebasejs/5.1.0/firebase-app.js">
</script>
<script src="https://www.gstatic.com/firebasejs/5.1.0/firebase-
messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyAR84lF2vbnfUWPZ2899dnqiTthgvfv7Ms",
authDomain: "lazemnicms.firebaseapp.com",
databaseURL: "https://lazemnicms.firebaseio.com",
projectId: "lazemnicms",
storageBucket: "lazemnicms.appspot.com",
messagingSenderId: "268754114869"
};
firebase.initializeApp(config);
messaging = firebase.messaging();
//Registering the service worker
navigator.serviceWorker.register("firebase-messaging-sw.js", {scope: "firebase-cloud-messaging-push-scope"}).then(function (registration) {
messaging.useServiceWorker(registration);
}).catch(function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
permissionGranted = false;
messaging.getToken().then(function(currentToken) {
if (currentToken) {
console.log(currentToken);
permissionGranted = true;
//sendTokenToServer(currentToken);
//updateUIForPushEnabled(currentToken);
} else {
permissionGranted = false;
}
}).catch(function(err) {
permissionGranted = false;
});
And also if a user got a refreshedToken, how can i know this user's old token so i can remove it from my database after i store his/her new token?
Those questions are really troubling me.
Thanks in advance.
The v1 API currently only allows sending to a single token at a time. Multicast is planned to be added (it was present in the previous API), but I don't have a timeline for when it will be available. So right now that means that you'll need to do a call to the FCM API for each token.
There is nothing built-in to know the previous token for a user. The typical way to do this is to keep the "last known token" in local storage, and unregister that when you get a new token. Alternatively, you can instead catch the errors that indicate an invalid token when sending messages, and remove them from the database that way (see an example of that here). A combination of these two approaches is probably best.

Firebase listener onAuthStateChanged not triggered on S3 Website

I simply re-implemented OAUTH2 with Instagram and Firebase with the serverless framework. I took inspiration from this project:
https://github.com/firebase/custom-auth-samples/tree/master/instagram
I am hosting the main page index.html on a public S3 bucket.
My API functions are good, I am receiving the exact same content as with my local testing with the repository above. I have all the tokens that my app need (instagram token, firebase token...) so it looks all good from a server perspective.
The last call is returning this piece of HTML:
<script src="https://www.gstatic.com/firebasejs/3.6.0/firebase.js" </script>
<script>
var token = 'firebase_token_yyy';
var config = {
apiKey: 'firebase_api_key_xxx'
};
var app = firebase.initializeApp(config);
app.auth().signInWithCustomToken(token).then(function() {
window.close();
});
</script>
This is well executed as it is closing the pop-up for logging.
However, onAuthStateChanged is not triggered (https://github.com/firebase/custom-auth-samples/blob/master/instagram/public/main.js#L41).
This is weird since the main.js code was well initialized when opening index.html.
I also tried running a simple manual web server: same behavior.
Would it be related to AWS S3 ?
I also though that the browser would propagate the state across windows ?
There is no javascript error and the hostname was whitelisted for Firebase Oauth.

Resources