萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 Notification API 實戰:構建桌面級 Web 通知系統完整指南

前言:原生通知能力的覺醒

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

核心 API 速覽

1. 權限請求


Notification.requestPermission().then(permission => {
  // permission: 'granted' | 'denied' | 'default'
  if (permission === 'granted') { /* 可以發送通知 */ }
});

返回 Promise(現代寫法),舊版回調兼容:Notification.requestPermission(cb)。

2. 創建通知


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' } // 任意數據,點擊事件可取用
});

3. 事件監聽


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 => { ... });

完整可用 Demo(含權限引導、按鈕觸發、自動關閉)


<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>

進階實戰:Service Worker + Push API 實現離線推送

Notification API 僅解決「前台展示」。要實現**應用關閉/瀏覽器關閉也能收到推送**,需結合:

  1. Service Worker:註冊 SW,監聽 push 事件;
  2. Push API:向應用服務器訂閱 PushSubscription,獲取端點;
  3. 應用服務器:使用 VAPID 密鑰加密負載,發送至瀏覽器推送服務;
  4. SW 中展示:self.registration.showNotification(title, options)。

完整流程超出本文範圍,參考 Web.dev Push Notifications 指南。

最佳實踐清單

  • ✅ **只在用戶明確交互後請求權限**(點擊鈴鐺圖標、設置頁面),避免入站即彈窗被瀏覽器攔截/用戶拒絕;
  • ✅ **圖標準備多尺寸**(72×72, 192×192, 512×512),適配不同平台;
  • ✅ **使用 tag 去重**,避免同類通知疊加刷屏;
  • ✅ **關鍵信息放在 body**,標題控制在 50 字內;
  • ✅ **提供 actions 讓用戶不打開頁面即可完成高頻操作**(如「標記已讀」、「稍後提醒」);
  • ✅ **數據最小化**:data 僅傳遞必要標識,敏感信息走點擊後接口獲取;
  • ✅ **優雅降級**:權限被拒/不支援時,改用頁面內 Toast/彈窗/紅點提醒。

Notification API 讓 Web 應用跨越瀏覽器邊界,觸達用戶系統級注意力。合理使用權限請求時機、豐富通知內容、結合 Service Worker 實現全生命週期推送,是構建高留存 Web 產品的關鍵一環。

copyright © 萬盛學電腦網 all rights reserved