Service workers can be used to enable push notifications for a web application. Push notifications are a way for a web application to receive messages from a server even when the web application is not actively open in a browser.
To use service workers to enable push notifications for a web application, you need to do the following steps:
- Register the service worker in your web application. This is typically done in the main JavaScript file of the web application, using the
navigator.serviceWorker.register()
method. - In the service worker script, use the
self.registration.pushManager.subscribe()
method to subscribe the web application to push notifications. This method returns aPushSubscription
object, which contains the endpoint URL of the push service and a unique key that identifies the subscription. - Send the
PushSubscription
object to your server, so that it can use it to send push notifications to the web application. - In the service worker script, listen for the
push
event and use theself.registration.showNotification()
method to display a notification to the user when a push notification is received.
Here is an example of a service worker that enables push notifications for a web application:
self.addEventListener('push', event => {
const data = event.data.json();
const title = data.title;
const options = {
body: data.body,
icon: '/images/icon.png'
};
event.waitUntil(self.registration.showNotification(title, options));
});
In this example, the service worker listens for the push
event and displays a notification to the user with the title and body of the push notification.
Show Notification on Client Side
To use Firebase to send push notifications to a web application through a service worker, you need to do the following steps:
- Set up a Firebase project and enable the Cloud Messaging service in the Firebase console.
- Install the Firebase JavaScript library in your web application, and use it to initialize Firebase with your project’s configuration.
- Register the service worker in your web application. This is typically done in the main JavaScript file of the web application, using the
navigator.serviceWorker.register()
method. - In the service worker script, use the
self.registration.pushManager.subscribe()
method to subscribe the web application to push notifications. This method returns aPushSubscription
object, which contains the endpoint URL of the push service and a unique key that identifies the subscription. - Send the
PushSubscription
object to your server, so that it can use it to send push notifications to the web application using the Firebase Cloud Messaging API. - In the service worker script, listen for the
push
event and use theself.registration.showNotification()
method to display a notification to the user when a push notification is received.
Here is an example of a service worker that uses Firebase to send push notifications to a web application:
importScripts('https://www.gstatic.com/firebasejs/7.14.3/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.3/firebase-messaging.js');
firebase.initializeApp({
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
projectId: '<your-project-id>',
storageBucket: '<your-storage-bucket>',
messagingSenderId: '<your-messaging-sender-id>',
appId: '<your-app-id>',
measurementId: '<your-measurement-id>'
});
const messaging = firebase.messaging();
self.addEventListener('push', event => {
const data = event.data.json();
const title = data.title;
const options = {
body: data.body,
icon: '/images/icon.png'
};
event.waitUntil(self.registration.showNotification(title, options));
});
In this example, the service worker uses the Firebase JavaScript library to initialize Firebase with the project’s configuration, and uses the Firebase Cloud Messaging API to receive push notifications.
When a push notification is received, it displays a notification to the user with the title and body of the push notification.
Send Push Notification to Devices
To send a push notification to a specific device using a service worker and Firebase, you will need to use the device’s push notification token.
The push notification token is a unique identifier that is generated by the device’s push notification service (e.g. FCM for Android devices, APNS for iOS devices) and is used to identify the device when sending push notifications.
To send a push notification to a specific device using a service worker and Firebase, you need to do the following steps:
- Set up a Firebase project and enable the Cloud Messaging service in the Firebase console.
- Install the Firebase JavaScript library in your web application, and use it to initialize Firebase with your project’s configuration.
- Register the service worker in your web application. This is typically done in the main JavaScript file of the web application, using the
navigator.serviceWorker.register()
method. - In the service worker script, use the
messaging.getToken()
method of the Firebase Cloud Messaging API to get the device’s push notification token. - Send the push notification token to your server, so that it can use it to send a push notification to the specific device using the Firebase Cloud Messaging API.
- On your server, use the
sendToDevice()
method of the Firebase Cloud Messaging API, and pass it the push notification token and the payload of the push notification as arguments.
Here is an example of how to send a push notification to a specific device using a service worker and Firebase:
// On the client (web application)
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
const messaging = firebase.messaging();
messaging.getToken().then(token => {
// Send the token to the server
fetch('/send-notification', {
method: 'POST',
body: JSON.stringify({ token: token }),
headers: {
'Content-Type': 'application/json'
}
});
});
});
// On the server
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
exports.fulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
function sendNotification(agent) {
// Get the push notification token from the request body
const token = request.body.token;
// Create the message payload
const payload = {
notification: {
title: 'New message',
body: 'You have a new message'
}
};
// Send the push notification to the specific device
return admin.messaging().sendToDevice(token, payload);
}
let intentMap = new Map();
intentMap.set('Send Notification', sendNotification);
agent.handleRequest(intentMap);
});
In this example, the client (web application) subscribes to push notifications and sends the PushSubscription
object to the server.
The server then uses the Firebase Cloud Messaging API to send a push notification to the web application with the specified message payload.
How to Customize Message Notification UI/UX
To customize the UI of a push notification that is displayed to the user through a service worker, you can use the options object of the self.registration.showNotification()
method.
The options object allows you to specify various properties of the notification, such as the title, body, icon, and actions.
To customize the UI of a push notification that is displayed to the user through a service worker, you can use the following properties of the options object:
title
: The title of the notification.body
: The body of the notification.icon
: The URL of an image to use as the notification’s icon.image
: The URL of an image to use as the notification’s main image.actions
: An array of action objects, which represent buttons that the user can click on the notification.
Here is an example of a service worker that displays a customized push notification to the user:
self.addEventListener('push', event => {
const data = event.data.json();
const title = data.title;
const options = {
body: data.body,
icon: '/images/icon.png',
image: '/images/image.png',
actions: [
{ action: 'view', title: 'View' },
{ action: 'close', title: 'Close' }
]
};
event.waitUntil(self.registration.showNotification(title, options));
});
In this example, the service worker displays a notification to the user with a title, body, icon, image, and two actions (buttons).