Friday, December 21, 2018

Javascript : Setup Firebase cloud messaging app

The FCM JavaScript API lets you receive notification messages in web apps running in browsers that support the Push API.
Send messages to JavaScript clients using the HTTP and XMPP app server protocols, as described in Send Messages https://firebase.google.com/docs/cloud-messaging/send-message

An important note: The FCM SDK is supported only in pages served over HTTPS. This is due to its use of service workers, which are available only on HTTPS sites. Need a provider? Firebase Hosting is an easy way to get free HTTPS hosting on your own domain.

There are main two steps in enabling the Javascript to receive push notifications

1. Add firebase to the app
2. configure web credentials with FCM
3. add logic to access registration tokens

Adding the FCM to the firebase app is pretty straightforward.

The FCM Web interface uses Web credentials called "Voluntary Application Server Identification," or "VAPID" keys, to authorize send requests to supported web push services. To subscribe your app to push notifications, you need to associate a pair of keys with your Firebase project. You can either generate a new key pair or import your existing key pair through the Firebase Console.


Below are the steps to generate keypair

1. Open the Cloud Messaging tab of the Firebase console Settings pane and scroll to the Web configuration section.
2. In the Web Push certificates tab, click Generate Key Pair. The console displays a notice that the key pair was generated, and displays the public key string and date added.

Next step is to configure browser to receive push messages.

We need to add web app manifest that specifies gcm_sender_id. This is a hardcoded value indicating that FCM is authorised to send messages to this app.


The sample project that is given by Google for messaging is good enough to understand this,

1. First we need to request for permission
2. Get the token Instance ID token (IID), send it to server
3. now push from message from the server.

function requestPermission() {
    console.log('Requesting permission...');
    // [START request_permission]
    messaging.requestPermission().then(function() {
      console.log('Notification permission granted.');
      // TODO(developer): Retrieve an Instance ID token for use with FCM.
      // [START_EXCLUDE]
      // In many cases once an app has been granted notification permission, it
      // should update its UI reflecting this.
      resetUI();
      // [END_EXCLUDE]
    }).catch(function(err) {
      console.log('Unable to get permission to notify.', err);
    });
    // [END request_permission]
  }


messaging.getToken().then(function(currentToken) {
      if (currentToken) {
        sendTokenToServer(currentToken);
        updateUIForPushEnabled(currentToken);
      } else {
        // Show permission request.
        console.log('No Instance ID token available. Request permission to generate one.');
        // Show permission UI.
        updateUIForPushPermissionRequired();
        setTokenSentToServer(false);
      }
    }).catch(function(err) {
      console.log('An error occurred while retrieving token. ', err);
      showToken('Error retrieving Instance ID token. ', err);
      setTokenSentToServer(false);
    });

function deleteToken() {
    // Delete Instance ID token.
    // [START delete_token]
    messaging.getToken().then(function(currentToken) {
      messaging.deleteToken(currentToken).then(function() {
        console.log('Token deleted.');
        setTokenSentToServer(false);
        // [START_EXCLUDE]
        // Once token is deleted update UI.
        resetUI();
        // [END_EXCLUDE]
      }).catch(function(err) {
        console.log('Unable to delete token. ', err);
      });
      // [END delete_token]
    }).catch(function(err) {
      console.log('Error retrieving Instance ID token. ', err);
      showToken('Error retrieving Instance ID token. ', err);
    });

  }

Now to send the message below is what to be done

curl -X POST -H "Authorization: key=3MGdZowXUqtwFW58QeINgjvMIIWKcpu8mXJbFgudZe-FOLVRY3jaeQ8yn8B_uYfC_ClQA1Tv5Oas7QIxC8PISJbB2R79DwRpoDXKbRkbGh0CJN7Ydau-jLtkQG-7PR1w" -H "Content-Type: application/json" -d '{
  "notification": {
    "title": "Portugal vs. Denmark",
    "body": "5 to 1",
    "icon": "firebase-logo.png",
    "click_action": "http://localhost:8081"
  },
  "to": "-7Hii2UuMYiovu2MKEsiFCcqaC2gXIKlPVN1zrmMR7yca153Qw5tgoR1_gnrmMH-fucXLX9a6X6WEnh8fBaRzN7MHnwqzfDmShB_NgzQBu2sEpIPuVrL4MrcDZCf"
}' "https://fcm.googleapis.com/fcm/send"

references:
https://github.com/firebase/quickstart-js/blob/405fdde76b292f361e568e553de5d2b696c62b50/messaging/README.md

No comments:

Post a Comment