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?
问题:
回答1:
I'd never tried this before, but it's actually remarkably simple.
There are two things you need to know for this:
- How to send a HTTP request to Firebase Cloud Messaging to deliver a message
- How to call an external HTTP API from with Apps Script
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:
- shows up automatically in the system tray when the app is not active
- is not displayed when the app is active
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 theAuthorization
header will need to match the one for your Firebase project. See Firebase messaging, where to get Server Key?