LEARNING OBJECTIVES ⌵
- Construct and dispatch native OS notifications using the
new Notification(title, options)constructor. - Implement visual asset properties including
icon,image, andbadgeaccording to multi-DPI platform specifications. - Attach custom serializable application payloads and state using the
dataattribute. - Configure internationalization properties including text direction (
dir) and language tags (lang).
📖 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
optionspayload object conforming to the W3CNotificationOptionsdictionary. - Line 183:
requireInteraction: reqIntIn.checkedinstructs 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
+────────────────────────────────────────────────────────────+
| 🎨 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:
Create a function
dispatchOrderShippedAlert(order)that takes an order object with shape:Construct and trigger a
new Notificationwith:- 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
trueiforder.priorityistrue, otherwisefalse. - Data: Attach
{ orderId: order.id, customer: order.customer, timestamp: Date.now() }.
- Title:
If permission is not granted, request permission first.
🏁 Starter Code Sandbox
⚠️ Common Pitfalls
- 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. - Assuming
imageWorks on macOS: macOS UNUserNotificationCenter ignores theimage(hero banner) property entirely. Keep your core message insidebodyand never rely solely on an image banner to convey critical info. - Non-Cloneable Data in
data: Thedataproperty is serialized using the Structured Clone Algorithm. Passing objects containing DOM nodes, active WebSockets, or functions will throw aDataCloneError.
💡 Pro Tips
- Android Status Bar Mask (Badge): The
badgeicon 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. - Epoch Time Synchronization: Use the
timestampoption (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. icondisplays the main square avatar/logo (192x192 px), whileimagedisplays a wide hero banner (supported on Windows and Android).badgeprovides a monochrome status icon specifically for Android's system status bar.requireInteraction: truekeeps the desktop notification pinned until user dismissal on supported operating systems.- The
dataproperty allows arbitrary structured data to be attached and retrieved during lifecycle events. - --