Master Web Push Notifications: A Frontend Guide to Timely, Relevant Alerts
This article introduces Web Push Notifications, explains how they work with Service Workers, compares the Push and Notification APIs, provides code examples for displaying notifications, and lists resources for trying out push features in modern browsers.
Web Push Notifications bring native‑app‑like alert capabilities to web pages, allowing sites to reach users even when the browser is closed.
Push is built on Service Workers, which run in the background and handle incoming messages; the Notification API then displays alerts to the user.
Is it related to Service Worker?
Yes, push relies on a Service Worker because the worker operates in the background and only runs code when the user interacts with a notification, minimizing battery usage.
Two Technologies
The Push API delivers messages to the Service Worker, while the Notification API lets the Service Worker or page scripts present information to the user.
Push API reference: https://developer.mozilla.org/en-US/docs/Web/API/Push_API
Notification API reference: https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API
Code Example
After registering a Service Worker, you can call showNotification on the registration object:
<code>serviceWorkerRegistration.showNotification(title, options);</code>Parameters:
title : the notification title.
options : an object defining other properties, e.g.:
<code>{
"body": "Did you make a $1,000,000 purchase at Dr. Evil...",
"icon": "images/ccard.png",
"vibrate": [200, 100, 200, 100, 200, 100, 400],
"tag": "request",
"actions": [
{"action": "yes", "title": "Yes", "icon": "images/yes.png"},
{"action": "no", "title": "No", "icon": "images/no.png"}
]
}</code>This code generates a notification similar to the example image below.
How to Try It
Explore the official sample repository: https://github.com/GoogleChrome/samples/tree/gh-pages/push-messaging-and-notifications
Use Peter Beverloo's notification generator: https://tests.peter.sh/notification-generator/
Check Mozilla's push payload demo: https://serviceworke.rs/push-payload_demo.html
Tip: The Push API requires a secure context (HTTPS) unless you are testing on localhost .
Yuewen Frontend Team
Click follow to learn the latest frontend insights in the cultural content industry. We welcome you to join us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.