Chapter 53: Web Notifications API & Native Push

Creating Desktop Notifications

Configure native desktop visual payloads using the Notification constructor, body copy, app icons, hero images, monochrome status badges, and metadata payloads.

LEARNING OBJECTIVES
  • Construct and dispatch native OS notifications using the new Notification(title, options) constructor.
  • Implement visual asset properties including icon, image, and badge according to multi-DPI platform specifications.
  • Attach custom serializable application payloads and state using the data attribute.
  • Configure internationalization properties including text direction (dir) and language tags (lang).
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

📖 The Mental Model & Story (Intuitive Foundation)

Think of a native notification like sending a formatted physical parcel through the postal service. A simple letter just has a recipient name and a message. But a high-priority certified package includes a sender seal, a preview photo of the contents, a status label, and a custom tracking barcode.

+─────────────────────────────────────────────────────────────────────────────+
|                        DESKTOP NOTIFICATION ANATOMY                         |
+─────────────────────────────────────────────────────────────────────────────+
|                                                                             |
|  +-----------------------------------------------------------------------+  |
|  | [icon]  TITLE: John Doe sent a message                       [10:30 AM]|  |
|  | (Avatar)                                                              |  |
|  |         BODY: "Hey! Can you review the quarterly deployment pull      |  |
|  |         request when you get a chance?"                               |  |
|  |                                                                       |  |
|  | +-------------------------------------------------------------------+ |  |
|  | |                                                                   | |  |
|  | |                      [image] (Hero Banner)                        | |  |
|  | |                 High-Resolution Chart / Preview                   | |  |
|  | |                                                                   | |  |
|  | +-------------------------------------------------------------------+ |  |
|  |                                                                       |  |
|  |  [badge] (Android Status Bar)  │  [data: { conversationId: "c-481" }] |  |
|  +-----------------------------------------------------------------------+  |
|                                                                             |
+─────────────────────────────────────────────────────────────────────────────+

When you instantiate new Notification(title, options), you aren't rendering HTML or CSS. You are supplying a structured dictionary to the operating system's native graphics subsystem. The operating system takes your text, fetches your image URLs, and places them into its proprietary system UI containers.


Technical Deep Dive & Specifications

The NotificationOptions Dictionary

The W3C specification defines the complete configuration dictionary passed as the second parameter to new Notification(title, options):

dictionary NotificationOptions {
  NotificationDirection dir = "auto";
  DOMString lang = "";
  DOMString body = "";
  DOMString tag = "";
  USVString image;
  USVString icon;
  USVString badge;
  VibratePattern vibrate;
  EpochTimeStamp timestamp;
  boolean renotify = false;
  boolean silent = false;
  boolean requireInteraction = false;
  any data = null;
  sequence<NotificationAction> actions = [];
};

Visual Asset Specifications & Platform Nuances

Property Purpose Recommended Resolution Platform Behavior & Notes
icon Main brand logo or sender profile avatar 192 x 192 px (Square PNG/WebP) Shown on Windows Action Center (left/right), macOS banner (right), Android drawer (large right icon).
image Large hero preview or content screenshot 720 x 360 px (2:1 aspect ratio) Rendered below body text in Windows 10/11 toasts and Android drawer. Ignored by macOS Notification Center.
badge Monochrome status symbol for small displays 96 x 96 px (Alpha mask PNG) Displayed on Android status bar when notification is present. Must contain white shapes on transparent background.
requireInteraction Keeps the notification on screen until dismissed Boolean On Windows/Chrome, prevents the toast from auto-hiding after 5-7 seconds. Useful for critical 2FA codes or VoIP calls.
data Custom metadata attachment Any structured cloneable data Carried throughout the notification lifecycle. Accessible in event handlers (event.target.data).
dir & lang Text direction and localization 'ltr', 'rtl', 'auto' Sets layout flow and typography rules for internationalization (e.g., lang: 'ar-EG', dir: 'rtl').

Cross-Platform Layout Variations

+─────────────────────────────────────────────────────────────────────────+
|                  CROSS-PLATFORM RENDERING MATRIX                        |
+─────────────────────────────────────────────────────────────────────────+
|  Feature             | Windows 10/11 | macOS Sonoma | Android 14 | iOS 16.4+ (PWA) |
|──────────────────────┼───────────────┼──────────────┼────────────┼─────────────────|
|  `title` & `body`    |  ✅ Full      |  ✅ Full     |  ✅ Full   |  ✅ Full        |
|  `icon` (Avatar)     |  ✅ Supported |  ✅ Supported|  ✅ Supported|  ✅ Supported  |
|  `image` (Hero View) |  ✅ Supported |  ❌ Ignored  |  ✅ Supported|  ❌ Ignored     |
|  `badge` (Status)    |  ❌ Ignored   |  ❌ Ignored  |  ✅ Supported|  ❌ Ignored     |
|  `requireInteraction`|  ✅ Supported |  ⚠️ System DND| ✅ Supported|  ❌ Unsupported |
+─────────────────────────────────────────────────────────────────────────+

💻 Interactive Code Playground

Starter Code

Save this file as index.html and run it in a local web server with permissions granted:

Line-by-Line Code Breakdown

  • Lines 176–188: Constructs the options payload object conforming to the W3C NotificationOptions dictionary.
  • Line 183: requireInteraction: reqIntIn.checked instructs the host OS (on Windows and Chrome) to keep the toast on screen until the user explicitly dismisses or clicks it.
  • Lines 185–188: data: { ... } injects custom application metadata (deployment IDs, routing URLs, or timestamps) that survives the IPC transfer and is readable from event handlers.
  • Line 191: new Notification(titleIn.value, options) executes the constructor, triggering the host OS notification bridge.

Expected Browser Render Output


SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL playground.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...
+────────────────────────────────────────────────────────────+
| 🎨 Notification Payload Studio                             |
| Configure rich desktop notification options...             |
|                                                            |
| [ Title: 🚀 Production Build Deployed                    ] |
| [ Body: Version v2.4.0 is now live across all 12...      ] |
| [ Icon URL: ... ]                 [ Image URL: ... ]       |
| [ Direction: LTR ]                [ Language: en-US ]      |
| [x] Require User Interaction (Sticky on Windows/Chrome)    |
|                                                            |
| [ Dispatch Native Desktop Notification (Blue CTA) ]        |
|                                                            |
| LIVE STRUCTURAL PREVIEW                                    |
| +────────────────────────────────────────────────────────+ |
| | [Icon] 🚀 Production Build Deployed                    | |
| |        Version v2.4.0 is now live across all 12...     | |
| |        +─────────────────────────────────────────────+ | |
| |        |             [Hero Image Banner]             | | |
| |        +─────────────────────────────────────────────+ | |
| +────────────────────────────────────────────────────────+ |
+────────────────────────────────────────────────────────────+

🏋️ Hands-On Exercise

🎯 The Challenge: E-Commerce Dispatch Alert Builder

Instructions:

  1. Create a function dispatchOrderShippedAlert(order) that takes an order object with shape:

  2. Construct and trigger a new Notification with:

    • Title: "📦 Order #[id] Has Shipped!"
    • Body: "Hi [customer], your package with [itemsCount] items ($[total]) is on its way."
    • Icon: "https://cdn-icons-png.flaticon.com/512/709/709790.png"
    • Require Interaction: Set to true if order.priority is true, otherwise false.
    • Data: Attach { orderId: order.id, customer: order.customer, timestamp: Date.now() }.
  3. If permission is not granted, request permission first.

🏁 Starter Code Sandbox

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
STARTER CODE SANDBOX exercise.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...

⚠️ Common Pitfalls

  1. Relative Image URLs in Worker Contexts: Using relative paths like icon: '/img/logo.png' can break depending on the base URL context. Always use root-relative or absolute HTTPS URLs.
  2. Assuming image Works on macOS: macOS UNUserNotificationCenter ignores the image (hero banner) property entirely. Keep your core message inside body and never rely solely on an image banner to convey critical info.
  3. Non-Cloneable Data in data: The data property is serialized using the Structured Clone Algorithm. Passing objects containing DOM nodes, active WebSockets, or functions will throw a DataCloneError.

💡 Pro Tips

  1. Android Status Bar Mask (Badge): The badge icon on Android requires a 96x96 PNG with pure white artwork and alpha transparency. Any colored pixels will be converted to a solid monochromatic silhouette by the Android OS.
  2. Epoch Time Synchronization: Use the timestamp option (Date.now()) when notifying users of historical or scheduled events (e.g. "Meeting started 5 minutes ago") so the host OS displays the accurate relative time.

📌 Key Takeaways

  • The new Notification(title, options) constructor creates and dispatches native OS alerts.
  • icon displays the main square avatar/logo (192x192 px), while image displays a wide hero banner (supported on Windows and Android).
  • badge provides a monochrome status icon specifically for Android's system status bar.
  • requireInteraction: true keeps the desktop notification pinned until user dismissal on supported operating systems.
  • The data property allows arbitrary structured data to be attached and retrieved during lifecycle events.
  • --
⭐ LEARN: HTML 🌟 ⚔️ QUIZ BATTLE ARENA // ACTIVE
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 1 / 3

Which property in the NotificationOptions dictionary prevents a desktop notification on Windows/Chromium from automatically disappearing after 5 seconds?

Question 1 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 2 / 3

What happens if you assign a function or active DOM element to the data property of a notification?

Question 2 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 3 / 3

Why should an Android notification badge asset be designed differently from an icon asset?

Question 3 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP