0
0
Firebasecloud~30 mins

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

Choose your learning style9 modes available
Notification handling in background
📖 Scenario: You are building a mobile app that needs to receive notifications even when the app is not open. This means the app must handle notifications in the background to alert users about important updates.
🎯 Goal: Create a Firebase Cloud Messaging (FCM) service worker script that handles notifications when the app is in the background. You will set up the initial service worker, configure notification options, implement the background message handler, and finalize the notification display.
📋 What You'll Learn
Create a service worker file named firebase-messaging-sw.js.
Initialize Firebase messaging in the service worker.
Add a configuration variable for notification title.
Implement the background message handler to show notifications.
Complete the notification display with icon and click action.
💡 Why This Matters
🌍 Real World
Mobile apps often need to notify users about updates even when the app is closed. Handling notifications in the background ensures users stay informed.
💼 Career
Understanding background notification handling is essential for mobile app developers and cloud engineers working with Firebase Cloud Messaging.
Progress0 / 4 steps
1
Create the Firebase messaging service worker
Create a file named firebase-messaging-sw.js and write the line importScripts('https://www.gstatic.com/firebasejs/9.22.1/firebase-app-compat.js'); to import Firebase app scripts.
Firebase
Need a hint?

This line imports Firebase app scripts needed for messaging in the service worker.

2
Add Firebase messaging import and initialize app
In firebase-messaging-sw.js, add the line importScripts('https://www.gstatic.com/firebasejs/9.22.1/firebase-messaging-compat.js'); to import messaging scripts. Then initialize Firebase app with firebase.initializeApp({messagingSenderId: '1234567890'});.
Firebase
Need a hint?

Import messaging scripts and initialize Firebase with your sender ID.

3
Implement background message handler with notification title
Create a constant notificationTitle with value 'Background Notification'. Then get messaging instance with const messaging = firebase.messaging();. Use messaging.onBackgroundMessage with a callback that receives payload and calls self.registration.showNotification(notificationTitle, {body: payload.data.body});.
Firebase
Need a hint?

Set notification title, get messaging instance, and handle background messages to show notifications.

4
Complete notification with icon and click action
In the showNotification call, add an icon property with value '/firebase-logo.png' and a data property containing click_action with value 'https://www.example.com' inside the options object.
Firebase
Need a hint?

Add icon and click action URL to the notification options for better user experience.