I want to write a little script that tells Firebase to push notification if a certain condition is met. How to send push notification from Firebase using google apps script?
Firebase Cloud Messaging (FCM) provides a reliable and battery-efficient connection between your server and devices that allows you to deliver and receive messages and notifications on iOS, Android, and the web at no cost.
I'd never tried this before, but it's actually remarkably simple.
There are two things you need to know for this:
Once you have read those two pieces of documentation, the code is fairly straightforward:
function sendNotificationMessage() {
var response = UrlFetchApp.fetch('https://fcm.googleapis.com/fcm/send', {
method: 'POST',
contentType: 'application/json',
headers: {
Authorization: 'key=AAAAIM...WBRT'
},
payload: JSON.stringify({
notification: {
title: 'Hello TSR!'
},
to: 'cVR0...KhOYB'
})
});
Logger.log(response);
}
In this case:
the script sends a notification message. This type of message:
If you want full control over what the app does when the message reaches the device, send a data message
the script send the message to a specific device, identified by its device token in the to
property. You could also send to a topic, such as /topics/user_TSR
. For a broader example of this, see my blog post on Sending notifications between Android devices with Firebase Database and Cloud Messaging.
the key
in the Authorization
header will need to match the one for your Firebase project. See Firebase messaging, where to get Server Key?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With