Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
The Notification API allows web pages to display system notifications to the user. These notifications appear outside the browser window, even when the page is not active, making them perfect for alerts, reminders, and real-time updates.
Notifications appear outside the browser in the OS notification center
Users must explicitly grant notification permission
Can include actions, images, and respond to clicks
// Check if notifications are supported
if (!('Notification' in window)) {
console.log('Notifications not supported');
} else {
// Check current permission status
console.log('Permission:', Notification.permission);
// Possible values: "granted", "denied", "default"
// Request permission (modern way with Promises)
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
console.log('Permission granted!');
} else if (permission === 'denied') {
console.log('Permission denied');
} else {
console.log('Permission dismissed');
}
});
// Old callback-based way (for compatibility)
Notification.requestPermission(permission => {
console.log('Permission:', permission);
});
}// Simple notification
if (Notification.permission === 'granted') {
new Notification('Hello!', {
body: 'This is a notification message',
icon: '/icon.png'
});
}
// Notification with all options
const notification = new Notification('New Message', {
body: 'You have a new message from John',
icon: '/avatar.png',
badge: '/badge.png', // Small icon shown in notification tray
image: '/preview.jpg', // Large preview image
tag: 'message-123', // Unique ID (replaces duplicate notifications)
requireInteraction: false, // Keep notification until user dismisses
silent: false, // Play notification sound
vibrate: [200, 100, 200], // Vibration pattern (mobile)
data: { // Custom data attached to notification
userId: 123,
messageId: 456
},
actions: [ // Action buttons (requires Service Worker)
{
action: 'reply',
title: 'Reply'
},
{
action: 'close',
title: 'Close'
}
]
});
// Listen to notification events
notification.onclick = () => {
console.log('Notification clicked');
window.focus(); // Focus the browser window
notification.close(); // Close the notification
};
notification.onclose = () => {
console.log('Notification closed');
};
notification.onerror = (error) => {
console.error('Notification error:', error);
};
notification.onshow = () => {
console.log('Notification shown');
};
// Close notification programmatically
setTimeout(() => {
notification.close();
}, 5000); // Close after 5 seconds| Option | Type | Description |
|---|---|---|
body | string | Notification message text |
icon | string (URL) | Icon image URL |
badge | string (URL) | Small badge icon for notification tray |
image | string (URL) | Large preview image |
tag | string | Unique ID (replaces existing notification with same tag) |
requireInteraction | boolean | Keep notification until user dismisses |
silent | boolean | No sound or vibration |
vibrate | array | Vibration pattern [vibrate, pause, vibrate, ...] |
data | any | Custom data attached to notification |
class NotificationManager {
constructor() {
this.supported = 'Notification' in window;
this.notifications = new Map();
}
// Check if notifications are supported
isSupported() {
return this.supported;
}
// Get current permission status
getPermission() {
if (!this.supported) return 'unsupported';
return Notification.permission;
}
// Request notification permission
async requestPermission() {
if (!this.supported) {
throw new Error('Notifications not supported');
}
if (Notification.permission === 'granted') {
return 'granted';
}
if (Notification.permission === 'denied') {
return 'denied';
}
// Request permission
const permission = await Notification.requestPermission();
return permission;
}
// Show a notification
async show(title, options = {}) {
// Ensure we have permission
if (Notification.permission !== 'granted') {
const permission = await this.requestPermission();
if (permission !== 'granted') {
throw new Error('Permission not granted');
}
}
// Create notification
const notification = new Notification(title, {
icon: '/icon.png',
...options
});
// Store reference
const id = options.tag || Date.now().toString();
this.notifications.set(id, notification);
// Setup event handlers
notification.onclick = (e) => {
console.log('Notification clicked:', id);
if (options.onClick) {
options.onClick(e);
}
window.focus();
notification.close();
};
notification.onclose = () => {
this.notifications.delete(id);
if (options.onClose) {
options.onClose();
}
};
// Auto-close after duration
if (options.duration) {
setTimeout(() => {
notification.close();
}, options.duration);
}
return {
id,
notification,
close: () => notification.close()
};
}
// Show success notification
success(message, options = {}) {
return this.show('✅ Success', {
body: message,
icon: '/success-icon.png',
tag: 'success',
...options
});
}
// Show error notification
error(message, options = {}) {
return this.show('❌ Error', {
body: message,
icon: '/error-icon.png',
tag: 'error',
requireInteraction: true,
...options
});
}
// Show info notification
info(message, options = {}) {
return this.show('ℹ️ Info', {
body: message,
icon: '/info-icon.png',
tag: 'info',
...options
});
}
// Close specific notification
close(id) {
const notification = this.notifications.get(id);
if (notification) {
notification.close();
}
}
// Close all notifications
closeAll() {
this.notifications.forEach(notification => {
notification.close();
});
this.notifications.clear();
}
}
// Usage
const notifier = new NotificationManager();
// Check support
if (notifier.isSupported()) {
console.log('Notifications are supported!');
}
// Request permission on user action
document.getElementById('enableBtn').addEventListener('click', async () => {
try {
const permission = await notifier.requestPermission();
console.log('Permission:', permission);
} catch (error) {
console.error('Error:', error);
}
});
// Show notifications
notifier.success('Data saved successfully!', {
duration: 3000
});
notifier.error('Failed to connect to server', {
onClick: () => {
console.log('User clicked error notification');
window.location.href = '/settings';
}
});
notifier.info('New update available', {
onClick: () => {
console.log('Checking for updates...');
},
duration: 5000
});
// Close all notifications
window.addEventListener('beforeunload', () => {
notifier.closeAll();
});Users must explicitly grant permission
Appears in OS notification center
Supports icons, images, and actions
Respond to clicks and closes