Introduction to Web Push Notifications
Push notifications are a crucial feature of Progressive Web Apps (PWAs) that keep users engaged by delivering timely updates even when the application is not open.
1. What Are Web Push Notifications?
Web push notifications are messages sent from a web application to a user’s device, even if the web page is not open. They allow PWAs to re-engage users with updates, reminders, and personalized messages.
Key Benefits of Web Push in PWAs:
- ✔️ Real-time engagement – Notify users of new content instantly.
- ✔️ Works offline – Notifications can be delivered even when the app is closed.
- ✔️ No app store dependency – Unlike mobile push notifications, no installation is needed.
2. How Web Push Works
A web push system consists of:
- Push Service: A third-party server (like Firebase Cloud Messaging - FCM) that delivers notifications to users.
- Service Worker: A script that listens for push events and displays notifications.
- Application Server: The Rails backend that sends notifications.
The process:
- The user grants notification permission in the PWA.
- The browser subscribes to the push service and receives a unique push token.
- The Rails backend sends a push request using this token.
- The service worker receives the push event and displays the notification.
3. User Permission for Notifications
Before sending notifications, the browser requires user permission.
Add this JavaScript to prompt the user:
function requestNotificationPermission() {
if ("Notification" in window && "serviceWorker" in navigator) {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
console.log("Notifications enabled");
} else {
console.log("Notifications denied");
}
});
}
}
Call this function when the PWA loads:
document.addEventListener("DOMContentLoaded", () => {
requestNotificationPermission();
});