Notifications: Grabbing Attention

Notifications: Grabbing Attention in JavaScript: The Notifications API lets websites show "Desktop Notifications" like a real app.

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

  1. The Permission Proofer: Write a script that checks the current permission status (Notification.permission) and displays "Thanks", "Blocked", or "Please Allow" accordingly.
  2. The Silent Nudger: Research the silent: true option for notifications and explain why a "Chat App" might use it.
  3. The Timed Alert: Create a "Pomodoro Timer" button that sends a notification "Time for a break!" after exactly 25 minutes.