w3resource

Desktop Notifications using JavaScript Web Notifications API

JavaScript Event Handling: Exercise-21 with Solution

Web Notifications API

Write a JavaScript program that sends a desktop notification to the user after getting permission..

Solution : Using Notification API

HTML and JavaScript Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>w3resource</title>
</head>
<body>
<script> 
// Check if the Notification API is supported in the browser
if ('Notification' in window) {
  // Request permission to send notifications
  Notification.requestPermission().then((permission) => {
    if (permission === 'granted') { // If permission is granted
      // Create and show a notification
      const notification = new Notification('Hello!', {
        body: 'This is your desktop notification.',
        icon: 'https://via.placeholder.com/48', // Optional icon
      });

      // Add a click event listener to the notification
      notification.onclick = () => {
        alert('Notification clicked!');
      };
    } else {
      alert('Notification permission denied.');
    }
  });
} else {
  console.error('Notifications are not supported in this browser.');
}

  </script>
</body>
</html>

Output:

JavaScript double click event: Using Notification API.

Note: Executed in JS Bin

Explanation:

    1. API Support Check:

    • Verifies if the Notification API is available in the browser.

    2. Permission Request:

    • Requests user permission to send notifications using Notification.requestPermission.

    3. Notification Creation:

    • Creates and displays a notification if permission is granted.

    4. Event Listener:

    • Adds a click event listener to handle user interaction with the notification.

Live Demo:

See the Pen javascript-event-handling-exercise-21 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that requests permission for notifications and displays a desktop notification with a custom message.
  • Write a JavaScript function that schedules a notification to appear after a delay using the Web Notifications API.
  • Write a JavaScript program that shows notifications with action buttons and handles user responses to those actions.
  • Write a JavaScript function that fetches dynamic content from an API and triggers a notification with that content, handling errors if permission is denied.

Go to:


PREV : Clipboard API for Copy.
NEXT : JavaScript functions Exercises Home.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.