Gmail、Slack、GitHub 等 Web 應用早已實現「頁面不在前台也能彈出通知」。HTML5 Notification API 提供標準化接口,無需 Electron/原生 App 封裝,即可獲得系統級通知權限。
Chrome 22+、Firefox 22+、Safari 6+(需用戶交互)、Edge 14+、Opera 25+。
移動端:Android Chrome 支援,iOS Safari 16.4+ 支援(需 PWA 安裝到主屏)。
開發前必查: Can I Use - Notifications
Notification.requestPermission().then(permission => {
// permission: 'granted' | 'denied' | 'default'
if (permission === 'granted') { /* 可以發送通知 */ }
});
返回 Promise(現代寫法),舊版回調兼容:Notification.requestPermission(cb)。
const notification = new Notification('標題', {
body: '正文內容', // 必填,通知主體
icon: '/icon-192.png', // 圖標,建議 192×192 PNG
badge: '/badge-72.png', // Android 狀態欄小圖標
image: '/cover.jpg', // 大圖(Chrome 56+)
tag: 'unique-id', // 去重標識,同 tag 覆蓋不疊加
dir: 'auto', // 'auto' | 'ltr' | 'rtl'
lang: 'zh-CN', // BCP 47 語言標籤
vibrate: [200, 100, 200], // 震動模式(移動端)
sound: '/notification.mp3', // 聲音(Chrome 已棄用,建議自行播放 Audio)
renotify: true, // 同 tag 替換時是否再次提醒
requireInteraction: false, // true: 不自動關閉,需用戶手動關閉
silent: false, // 靜默模式(無聲/無震動)
actions: [ // 交互按鈕(Chrome 48+)
{ action: 'reply', title: '回覆', icon: '/reply.png' },
{ action: 'archive', title: '歸檔' }
],
data: { url: 'https://example.com/msg/123' } // 任意數據,點擊事件可取用
});
notification.onclick = (e) => {
e.preventDefault(); // 防止默認聚焦行為
const url = e.target.data?.url;
if (url) window.open(url, '_blank');
notification.close();
};
notification.onclose = () => console.log('用戶關閉或自動消失');
notification.onerror = (err) => console.error('通知錯誤:', err);
// 手動關閉
// notification.close();
// 監聽動作按鈕點擊(Service Worker 中處理更可靠)
// self.addEventListener('notificationclick', e => { ... });
<button id="notifyBtn">發送測試通知</button>
<script>
document.addEventListener('DOMContentLoaded', () => {
const btn = document.getElementById('notifyBtn');
btn.addEventListener('click', async () => {
// 1. 特性檢測
if (!('Notification' in window)) {
alert('當前瀏覽器不支持 Notification API');
return;
}
// 2. 獲取權限
let permission = Notification.permission;
if (permission === 'default') {
permission = await Notification.requestPermission();
}
if (permission !== 'granted') {
alert('需要授權通知權限才能演示');
return;
}
// 3. 發送通知
const config = {
body: '感謝點擊!這是一條來自 HTML5 Notification API 的測試消息。',
icon: 'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/1f4bb.png',
tag: 'demo-notification',
requireInteraction: false, // 5秒後自動關閉
data: { timestamp: Date.now() }
};
const n = new Notification('🎉 通知測試', config);
// 4. 定時自動關閉(requireInteraction=false 時瀏覽器會自動關閉,這裡演示手動控制)
setTimeout(() => n.close(), 5000);
// 5. 點擊跳轉
n.onclick = () => {
window.focus();
n.close();
};
});
});
</script>
Notification API 僅解決「前台展示」。要實現**應用關閉/瀏覽器關閉也能收到推送**,需結合:
push 事件;PushSubscription,獲取端點;self.registration.showNotification(title, options)。完整流程超出本文範圍,參考 Web.dev Push Notifications 指南。
tag 去重**,避免同類通知疊加刷屏;body**,標題控制在 50 字內;actions 讓用戶不打開頁面即可完成高頻操作**(如「標記已讀」、「稍後提醒」);data 僅傳遞必要標識,敏感信息走點擊後接口獲取;Notification API 讓 Web 應用跨越瀏覽器邊界,觸達用戶系統級注意力。合理使用權限請求時機、豐富通知內容、結合 Service Worker 實現全生命週期推送,是構建高留存 Web 產品的關鍵一環。