Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Push Notifications

Notification Design and Click Handling

Design notifications users keep: showNotification options, tags, actions, notificationclick with client focus, app badges, quiet hours and permission etiquette.

Getting a push message to the screen is the technical part. Making it something the user is glad to receive is the design part, and the part that decides whether they keep the permission. This lesson covers every useful option of showNotification, how to react when the user taps a notification, how to avoid spamming, and a few rules for deciding what deserves a notification at all.

The options you will use

JavaScript
registration.showNotification("Order shipped", {
  body: "Your headphones will arrive on Thursday.",
  icon: "/icons/icon-192.png",
  badge: "/icons/badge-72.png",
  image: "/img/order-42.jpg",
  tag: "order-42",
  renotify: false,
  requireInteraction: false,
  silent: false,
  timestamp: Date.now(),
  lang: "en",
  dir: "ltr",
  actions: [
    { action: "track", title: "Track order" },
    { action: "dismiss", title: "Dismiss" }
  ],
  data: { url: "/orders/42" }
});
Option What it does
body The second line of text. Keep it under about 100 characters; platforms truncate.
icon Main picture, usually 192 px square. Use your brand or the sender's avatar.
badge A small monochrome icon (Android status bar). Transparent PNG, white shape.
image Large picture in the body. Supported on Chromium; ignored elsewhere.
tag Notifications with the same tag replace each other instead of stacking.
renotify With a reused tag, true alerts again; default false replaces silently.
requireInteraction Keeps the notification until the user acts (desktop Chrome). Use rarely.
actions Buttons. Chromium shows up to the platform limit (often two). Not on Safari or Firefox desktop.
data Any structured data, available again in the click event.

Because support differs, build for the lowest common denominator: the title, body, icon and a good data.url must carry the message, and actions are shortcuts only.

Try it: build options for each event type

Keep the design rules in one function so every notification looks consistent and respects limits. The function below is plain JavaScript, so it runs here.

JS One place for notification rules

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Replace, do not stack

If a chat sends fifty messages in a minute, fifty separate notifications are spam. Reusing a tag makes the newest replace the older one. Combined with a counter in the body ("5 new messages from Mia"), the user sees one tidy item. You can also read the notifications that are already showing and merge:

JavaScript
const existing = await self.registration.getNotifications({ tag: "chat-7" });
const count = existing.length ? (existing[0].data.count ?? 1) + 1 : 1;
await self.registration.showNotification("Mia", {
  tag: "chat-7",
  body: count + " new messages",
  data: { url: "/chats/7", count },
});

Handling the click

A notification that does nothing when tapped is a broken promise. In the service worker, listen for notificationclick, close the notification, then focus an existing window if one is open or open a new one:

JavaScript
self.addEventListener("notificationclick", (event) => {
  event.notification.close();
  const url = new URL(event.notification.data?.url ?? "/", self.location.origin).href;

  if (event.action === "dismiss") return;

  event.waitUntil(
    (async () => {
      const windows = await clients.matchAll({ type: "window", includeUncontrolled: true });
      for (const client of windows) {
        if (client.url === url && "focus" in client) return client.focus();
      }
      return clients.openWindow(url);
    })()
  );
});

Three details: openWindow only works inside a click handler (a user gesture), so call it there; resolving the URL against self.location.origin keeps notification data from sending users to another origin; and handling event.action lets different buttons lead to different places.

JS Focus or open: the decision

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real code uses client.navigate(url) followed by focus() for the "navigate existing window" branch, which is usually nicer than opening a duplicate window.

Badges on the app icon

The Badging API puts a number or dot on the installed app's icon, which is gentler than a notification:

JavaScript
// works in the page or in the service worker
if ("setAppBadge" in navigator) {
  await navigator.setAppBadge(unreadCount);   // 0 clears it too
  // navigator.clearAppBadge();
}

Update it in the push handler, and clear it when the user opens the relevant screen. Support: installed PWAs on Chromium desktop and Android, and on iOS and macOS Safari web apps.

When not to notify

Ask these questions before sending:

  1. Is it timely? If it can wait for the next visit, do not push it.
  2. Is it personal? Messages from people and updates to the user's own things are welcome; generic marketing is not.
  3. Is it actionable? The tap should land somewhere useful, deep-linked, not on the home page.
  4. Can the user control it? Offer categories (messages, orders, promotions) and quiet hours in your own settings.

Respect the signals: if a user dismisses ten notifications in a row, or revokes permission, treat it as a request to send less. Track opt-in rate, click rate and permission revocations as health metrics.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do notifications with the same tag do?

    A tag identifies a logical notification; a new one with the same tag replaces the old.
  2. 2. Why call event.notification.close() in notificationclick?

    Some platforms leave the notification visible after a click unless you close it.
  3. 3. Which API changes the number on the installed app's icon?

    The Badging API exposes navigator.setAppBadge and clearAppBadge.
  4. 4. Why should critical information not rely on notification actions?

    Treat actions as shortcuts; the title, body and click target must work without them.

Summary

  • Use tag to replace instead of stack, data to carry the click target, and keep text short.
  • Handle notificationclick: close, then focus or open the right window with a same-origin URL.
  • Use the Badging API for passive counts.
  • Do not rely on actions, images or requireInteraction working everywhere.
  • Send only timely, personal, actionable messages and give users control.

Next: PWA Performance Basics