Setting Up Push Notifications in PWAs
Introduction
Push notifications provide a way for PWAs (Progressive Web Apps) to send real-time updates to users, enhancing engagement and user experience. This lesson covers how to set up push notifications in your PWA effectively.
Key Concepts
Definitions
- Service Worker: A script that runs in the background and allows PWAs to handle push notifications.
- Push API: An API that enables the server to push notifications to the client.
- Notification API: Allows the app to display notifications to the user.
Step-by-Step Setup
1. Register a Service Worker
Register a service worker in your main JavaScript file.
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
});
});
}
2. Request Notification Permission
Request permission from the user to send notifications.
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
console.log('Notification permission granted.');
} else {
console.log('Notification permission denied.');
}
});
3. Subscribe to Push Notifications
Subscribe the user to push notifications via the service worker.
navigator.serviceWorker.ready.then(registration => {
const options = {
userVisibleOnly: true,
applicationServerKey: 'YOUR_PUBLIC_VAPID_KEY'
};
return registration.pushManager.subscribe(options);
}).then(subscription => {
console.log('User is subscribed:', subscription);
});
4. Handle Push Notifications
Listen for push events in the service worker.
self.addEventListener('push', event => {
const data = event.data ? event.data.json() : {};
const options = {
body: data.body,
icon: 'icon.png',
badge: 'badge.png'
};
event.waitUntil(
self.registration.showNotification(data.title, options)
);
});
Best Practices
- Always ask for permission before sending notifications.
- Keep notifications relevant and personalized.
- Implement a clear unsubscribe option.
- Test notifications across various devices and browsers.
FAQ
What browsers support Push Notifications?
Most modern browsers support push notifications, including Chrome, Firefox, and Edge. Safari has limited support.
Do push notifications work offline?
No, push notifications require a network connection to be delivered.
Can I send notifications to users on mobile and desktop?
Yes, as long as the user has granted permission and is subscribed to notifications.