Concept Explanation
The Notifications API lets websites show "Desktop Notifications" like a real app. This is great for emails, calendar alerts, or "Task Complete" messages.
Just like Geolocation, this requires Explicit User Permission. Modern browsers are very strict: you can only ask for permission after a user click (like a button).
Syntax or Core Structure
Notification.requestPermission().then(permission => {
if (permission === "granted") {
new Notification("New Message!", {
body: "Alice sent you a photo.",
icon: "/img/avatar.png"
});
}
});
Best Practices
- Don't Spam: If you send 10 notifications per minute, the user will "Block" your site immediately. Use them sparingly.
- Check for Support: Not all browsers support notifications. Always check
if ('Notification' in window). - Service Workers: For "Push" notifications (sent while the website is closed), you must use a Service Worker.
Practice Exercises
- The Permission Proofer: Write a script that checks the current permission status (
Notification.permission) and displays "Thanks", "Blocked", or "Please Allow" accordingly. - The Silent Nudger: Research the
silent: trueoption for notifications and explain why a "Chat App" might use it. - The Timed Alert: Create a "Pomodoro Timer" button that sends a notification "Time for a break!" after exactly 25 minutes.