push/showNotification()/notificationclick
A Web Push service worker receives the event, creates a visible notification from validated data, then focuses or opens an approved URL. Reliability depends on registration scope, event lifetime, update behavior, and coexistence with any worker the site already uses.
Choose scope before choosing a file name
A service-worker registration controls URLs within its scope. A worker served at /assets/push-sw.js normally receives a narrower default scope than a root worker at /service-worker.js. If click handling or other offline behavior needs root coverage, plan that relationship deliberately. The server can use the Service-Worker-Allowed response header to authorize a broader scope, but this should not replace a clear deployment layout.
Inspect existing registrations before installing another worker. Two libraries cannot independently own the same registration without coordination. Merge push listeners into the existing worker or use the integration sequence in the Web Push API and SDK documentation so one deployment does not erase caching, offline, or push behavior from another.
Register once and wait for a ready worker
const registration = await navigator.serviceWorker.register(
"/service-worker.js",
{scope: "/"}
);
await navigator.serviceWorker.ready;
console.log(registration.scope);
Registration success means the script was fetched and accepted, not necessarily that the new version controls the current page immediately. Inspect the installing, waiting, and active states. During an update, an older active worker may continue handling events until existing clients release it.
Extend the push event lifetime
self.addEventListener("push", (event) => {
event.waitUntil((async () => {
const payload = event.data ? event.data.json() : {};
const title = payload.title || "New update";
const options = {
body: payload.body || "Open the site for details.",
icon: "/icon-192.png",
data: {url: safeDestination(payload.url)}
};
await self.registration.showNotification(title, options);
})());
});
event.waitUntil() tells the browser that asynchronous work belongs to the event. Without it, the worker may stop before the notification promise settles. Keep the handler small: validate the payload, derive safe options, and display. Large network fetches make time-limited background execution less predictable.
Validate data before presentation or navigation
The payload is encrypted in transit according to Web Push rules, but your worker still needs a schema. The payload encryption and size guide defines the key roles, byte budget, and versioned message shape. Reject destinations outside approved origins or paths so campaign input cannot become an open redirect.
Keep sensitive account details out of lock-screen text. Encryption protects message content from the push service, but the final notification may be visible to anyone near the device.
Handle notification clicks without opening duplicates
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const target = event.notification.data?.url || "/";
event.waitUntil((async () => {
const windows = await clients.matchAll({type: "window", includeUncontrolled: true});
const existing = windows.find((client) => new URL(client.url).origin === self.location.origin);
if (existing) {
await existing.focus();
existing.postMessage({type: "PUSH_NAVIGATE", target});
return;
}
await clients.openWindow(target);
})());
});
Your page must handle any navigation message if you use this pattern. A simpler implementation can open the target directly, but should still check for an appropriate existing client and keep the destination inside the verified origin.
Deploy worker updates as production changes
Run the changed build through the Web Push release test matrix, then compare its responsibilities with the Web Push platform implementation boundary before production rollout.
Service-worker scripts are update-sensitive assets. Avoid immutable caching that prevents browsers from checking for a new version. Test the old-to-new transition with an existing subscription, not only a fresh profile. If you use skipWaiting() or clients.claim(), understand that immediate activation can change behavior in open tabs; use those methods because the update is compatible, not as a universal fix.
Version payload schemas so an older worker can safely receive a message sent during rollout. If the new server payload requires a new worker feature, stage the worker first and keep a backwards-compatible fallback.
Use a worker-specific verification checklist
- The script returns JavaScript with a successful status and no redirect.
- The registration scope covers the intended destinations.
- The expected worker is active, and no second library overwrote it.
- The push event fires and
event.dataparses under the agreed schema. showNotification()resolves under granted permission.- The click handler closes the alert, reuses a suitable client, and opens only approved URLs.
- A worker update preserves push behavior for previously subscribed browsers.
Primary implementation references
The MDN Service Worker API guide explains lifecycle and registration behavior. The W3C Push API defines delivery to a service worker, and MDN documents showNotification(). After implementation, use the step-by-step Web Push diagnostic to verify each boundary.