MDN self-hosted library · e01.org

ServiceWorkerRegistration: showNotification() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
navigator.serviceWorker.register("sw.js");

async function showNotification() {
  const result = await Notification.requestPermission();

  if (result === "granted") {
    const registration = await navigator.serviceWorker.ready;

    registration.showNotification("Vibration Sample", {
      body: "Buzz! Buzz!",
      icon: "../images/touch/chrome-touch-icon-192x192.png",
      vibrate: [200, 100, 200, 100, 200, 100, 200],
      tag: "vibration-sample",
    });
  }
}
js
self.addEventListener("notificationclick", (event) => {
  const notification = event.notification;

  // Close notification if we don't need it any more.
  notification.close();

  // Process our particular notification
  if (notification.tag === "vibration-sample") {
    // Use event.waitUntil to keep the service worker alive until the promise resolves
    event
      .waitUntil
      // Code to handle the particular event.
      ();
  }
});
js
const registration = await navigator.serviceWorker.ready;

await registration.showNotification("New photo from Alex", {
  body: "Alex shared a photo from today's hike.",
  badge: "/images/app-badge.png",
  icon: "/images/alex-avatar.png",
  image: "/images/hiking-photo.png",
});
js
registration.showNotification("New Message", {
  body: "You've got mail.",
  icon: "/images/icon.png",
  actions: [
    { action: "reply", title: "Reply" },
    { action: "dismiss", title: "Dismiss" },
  ],
});
js
self.addEventListener("notificationclick", (event) => {
  event.notification.close();

  if (event.action === "reply") {
    // handle reply
  } else if (event.action === "dismiss") {
    // handle dismiss
  }
});