Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send push notification from Firebase using google apps script?

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?

like image 902
TSR Avatar asked Feb 11 '17 09:02

TSR


People also ask

Can you send push notifications with Firebase?

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.


1 Answers

I'd never tried this before, but it's actually remarkably simple.

There are two things you need to know for this:

  1. How to send a HTTP request to Firebase Cloud Messaging to deliver a message
  2. 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:

  1. 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

  2. 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.

  3. the key in the Authorization header will need to match the one for your Firebase project. See Firebase messaging, where to get Server Key?

like image 64
Frank van Puffelen Avatar answered Oct 01 '22 14:10

Frank van Puffelen