0
0
Firebasecloud~15 mins

Notification handling in foreground in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Notification handling in foreground
📖 Scenario: You are building a mobile app that receives notifications from Firebase Cloud Messaging (FCM). You want to handle notifications properly when the app is open (in the foreground) so users see alerts immediately.
🎯 Goal: Set up Firebase Cloud Messaging in your app and write code to handle incoming notifications while the app is in the foreground.
📋 What You'll Learn
Initialize Firebase messaging in the app
Create a listener for foreground messages
Display notification data when a message arrives in the foreground
💡 Why This Matters
🌍 Real World
Apps often need to show notifications immediately when users are active. Handling foreground notifications improves user engagement and awareness.
💼 Career
Knowing how to handle Firebase notifications in the foreground is essential for mobile developers working with real-time messaging and user alerts.
Progress0 / 4 steps
1
Initialize Firebase messaging
Create a variable called messaging and assign it the Firebase messaging instance using firebase.messaging().
Firebase
Need a hint?

Use firebase.messaging() to get the messaging instance.

2
Set up foreground message listener
Add a listener using messaging.onMessage that takes a callback function with a parameter payload.
Firebase
Need a hint?

Use messaging.onMessage to listen for messages when the app is open.

3
Log notification data from payload
Inside the messaging.onMessage callback, access payload.notification.title and payload.notification.body and assign them to variables title and body respectively.
Firebase
Need a hint?

Use payload.notification.title and payload.notification.body to get notification details.

4
Display alert with notification title and body
Inside the messaging.onMessage callback, add a line to show an alert with the message: Notification: ${title} - ${body} using a template string.
Firebase
Need a hint?

Use alert with a template string to show the notification.