Create and handle desktop notifications with HTML button and JavaScript Notification API.

by haba713

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Notification API Example</title>
</head>
<body>
  <button id="notifyBtn">Notify me!</button>
  <p id="status">Click the button to request a notification.</p>
</body>
</html>

CSS

body {
  font-family: Arial, sans-serif;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
  background-color: #f0f0f0;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
}

button:hover {
  background-color: #0056b3;
}

p#status {
  margin-top: 20px;
  font-size: 14px;
  color: #333;
}

JavaScript

document.getElementById("notifyBtn").addEventListener("click", notifyMe);

function notifyMe() {
  const status = document.getElementById("status");

  // Check if the browser supports the Notification API
  if (!("Notification" in window)) {
    status.textContent = "This browser does not support desktop notifications.";
    return;
  }

  // Check if permission is already granted
  if (Notification.permission === "granted") {
    createNotification();
  }
  // If permission is not denied, request it
  else if (Notification.permission !== "denied") {
    Notification.requestPermission().then((permission) => {
      if (permission === "granted") {
        createNotification();
      } else {
        status.textContent = "Notification permission was denied.";
      }
    });
  } else {
    status.textContent = "Notifications are denied by the user.";
  }
}

function createNotification() {
  const status = document.getElementById("status");
  
  // Create a notification with options
  const options = {
    body: "This is a sample notification from the Notification API!",
    icon: "https://via.placeholder.com/96", // Example icon (96x96 as per MDN recommendation)
    badge: "https://via.placeholder.com/96", // Example badge for Android
    dir: "auto",
    lang: "en-US",
    tag: "sample-notification",
    requireInteraction: true, // Notification stays until user interacts
    silent: false // Allow sound/vibration
  };

  const notification = new Notification("Hello, World!", options);
  status.textContent = "Notification sent! Check your desktop notifications.";

  // Handle notification events
  notification.onclick = () => {
    status.textContent = "Notification clicked!";
  };

  notification.onclose = () => {
    status.textContent = "Notification closed.";
  };

  notification.onerror = () => {
    status.textContent = "Error displaying notification.";
  };

  notification.onshow = () => {
   ...