Client app setup to receive notifications

To allow your app to receive notifications in your browser, it will have to get permissions from the user. To do so, we will add a piece of code that will show a consent dialog to let the user grant your app permission to receive notifications in your browser.

We will add the componentWillMount() method to our index.jsx file present under the home directory, since we want to show the dialog once the user is successfully logged in to the app:

 componentWillMount() {
firebase.messaging().requestPermission()
.then(function() {
console.log('Permission granted.');
// you can write logic to get the registration token
// _this.getToken();
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
}

Note that you will need to import the firebase object using the following line:

import firebase from '../firebase/firebase-config';

Once you add the preceding code, restart your server and log in to the app. It should show the following dialog box to the users of your app:

Once user gives permissions then only your browser will receive the notifications.

Now, let's write a function to get the registration token:

 getToken() {
console.log("get token");
firebase.messaging().getToken()
.then(function (currentToken) {
if (currentToken) {
console.log("current token", currentToken)
// sendTokenToServer(currentToken);
//updateUI(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);
});
}

The preceding function will retrieve the current access token that will need to be sent to the server to subscribe for the notifications. You can implement logic to send this token to the server in the sendTokenToServer() method.

The registration token may change when your web app deletes the registration token or a user clears browser data. In case of the latter, will need to call getToken() to retrieve the new token. Since there are chances that the registration token might get changed, you should also monitor refresh token to get the new token. FCM fires a callback whenever a token is generated so that you can get a new token. The onTokenRefresh() callback fires whenever a new token is generated, so calling the getToken() method in its context ensures that you are having a current registration token. You can write a function like this:

 refreshToken() {
firebase.messaging().onTokenRefresh(function () {
firebase.messaging().getToken()
.then(function (refreshedToken) {
console.log('Token refreshed.');
// Indicate that the new Instance ID token has not
yet been sent to the
// app server.
//setTokenSentToServer(false);
Send Instance ID token to app server. Implement it
as per your requirement
//sendTokenToServer(refreshedToken);
// ...
})
.catch(function (err) {
console.log('Unable to retrieve refreshed token ',
err);
//showToken('Unable to retrieve refreshed token ',
err);
});
});
}

Once you get the token, you can send it to your app server by implementing a method like sendTokenToServer(refreshedToken) to store it and if you are using React and Firebase Realtime Database, you can directly store it in the database.

All these functions will be added to the index.jsx file. We will call the getToken() function from the componentWillMount() method, whereas refreshToken() will be called from constructor.

Now, after all this setup, we will add the actual functionality of receiving the messages in our client app.

Depending on the page status, whether it is running in the background or in the foreground (it has focus) or it is closed or hidden behind tabs, the behavior of messages differs.

In order to receive messages, a page must handle the onMessage() callback, and to handle onMessage(), there must be a Firebase messaging service worker defined in your app.

We will create a file called firebase-messaging-sw.js under the root directory of the project and write the following code in it:

importScripts('https://www.gstatic.com/firebasejs/4.1.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.1.1/firebase-messaging.js');

var config = {
messagingSenderId: "41428255555"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};

return self.registration.showNotification(notificationTitle,
notificationOptions);
});

Alternatively, you can specify an existing service worker with useServiceWorker.

Note that you will need to update the message senderId value, which you can get from the Firebase console for your project.

If you want to show a notification message when your web page is in the background, you need to set setBackgroundMessageHandler to handle the messages. You can also customize the message, such as setting a custom title and icon. You can check it in the preceding code snippet. The messages received while the app is in the background trigger a display notification in the browser.

Now you can handle the OnMessage() event on your web page. We will add a constructor in our index.js file so that it registers the callback on page load:

constructor(props) {
super(props);
//this.refreshToken();
firebase.messaging().onMessage(function (payload) {
console.log("Message received. ", payload);
// Update the UI to include the received message.
console.log("msg", payload);
// appendMessage(payload);
});
}

Now our client is ready to receive the notification messages. Let's configure our backend to send the notifications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset