Notification API(Notification API)
一、基本用法
1.1 检查支持
if ('Notification' in window) {
console.log('Notifications supported');
}
1.2 权限级别
console.log(Notification.permission);
1.3 请求权限
const permission = Notification.requestPermission();
console.log(permission);
async function requestPermission() {
const permission = await Notification.requestPermission();
console.log('Permission:', permission);
return permission;
}
二、创建通知
2.1 基本通知
if (Notification.permission === 'granted') {
const notification = new Notification('Hello', {
body: 'This is a notification',
icon: '/icon.png'
});
}
2.2 通知选项
const options = {
body: 'Notification content',
icon: '/icon.png',
badge: '/badge.png',
tag: 'notification-id',
renotify: true,
requireInteraction: false,
silent: false,
vibrate: [200, 100, 200],
timestamp: Date.now(),
lang: 'zh-CN',
dir: 'auto',
data: { url: '/page' },
actions: [
{ action: 'accept', title: 'Accept' },
{ action: 'reject', title: 'Reject' }
]
};
const notification = new Notification('Title', options);
三、事件处理
3.1 通知事件
const notification = new Notification('Title', options);
notification.addEventListener('click', (event) => {
console.log('Notification clicked');
window.focus();
notification.close();
});
notification.addEventListener('close', (event) => {
console.log('Notification closed');
});
notification.addEventListener('show', (event) => {
console.log('Notification shown');
});
notification.addEventListener('error', (event) => {
console.error('Notification error');
});
3.2 自动关闭
const notification = new Notification('Title', {
body: 'Auto close in 5 seconds',
requireInteraction: false
});
setTimeout(() => {
notification.close();
}, 5000);
四、Service Worker 中的通知
4.1 发送后台通知
self.addEventListener('push', (event) => {
const data = event.data ? event.data.json() : {};
const options = {
body: data.body || 'New notification',
icon: data.icon || '/icon.png',
badge: data.badge || '/badge.png',
tag: data.tag || 'default',
data: data.data || {},
actions: data.actions || [],
requireInteraction: data.requireInteraction || false
};
event.waitUntil(
self.registration.showNotification(data.title || 'Notification', options)
);
});
4.2 通知点击处理
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const url = event.notification.data?.url || '/';
event.waitUntil(
clients.matchAll({ type: 'window', includeUncontrolled: true })
.then((clientList) => {
for (const client of clientList) {
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
return clients.openWindow(url);
})
);
});
4.3 通知关闭处理
self.addEventListener('notificationclose', (event) => {
console.log('Notification closed by user');
});
五、权限管理
5.1 Permissions API
async function checkPermission() {
const result = await navigator.permissions.query({ name: 'notifications' });
console.log('Permission state:', result.state);
result.addEventListener('change', () => {
console.log('Permission changed to:', result.state);
});
}
5.2 权限请求最佳实践
async function ensureNotificationPermission() {
if (Notification.permission === 'granted') {
return true;
}
if (Notification.permission === 'denied') {
console.warn('Notifications are blocked');
return false;
}
const permission = await Notification.requestPermission();
return permission === 'granted';
}
六、实际应用
6.1 消息通知服务
class NotificationService {
constructor() {
this.permission = Notification.permission;
}
async init() {
if (this.permission === 'default') {
this.permission = await Notification.requestPermission();
}
return this.permission === 'granted';
}
show(title, options = {}) {
if (this.permission !== 'granted') {
console.warn('Notification permission not granted');
return null;
}
return new Notification(title, {
icon: '/icon.png',
badge: '/badge.png',
...options
});
}
success(message, options = {}) {
return this.show('Success', {
body: message,
tag: 'success',
...options
});
}
error(message, options = {}) {
return this.show('Error', {
body: message,
tag: 'error',
requireInteraction: true,
...options
});
}
info(message, options = {}) {
return this.show('Info', {
body: message,
tag: 'info',
...options
});
}
}
const notifier = new NotificationService();
参考资料
延展阅读