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.


Improve this sample solution and post your code through Disqus.

Event Handling Exercises Previous: JavaScript Clipboard API: Copy Text from Input Box.
JavaScript functions Exercises Next: JavaScript functions Exercises Home.

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.