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:
Note: Executed in JS Bin
Explanation:
- Verifies if the Notification API is available in the browser.
- Requests user permission to send notifications using Notification.requestPermission.
- Creates and displays a notification if permission is granted.
- Adds a click event listener to handle user interaction with the notification.
1. API Support Check:
2. Permission Request:
3. Notification Creation:
4. Event Listener:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics