跳轉至

建立 2026-11-23 更新 2026-11-23

推播通知

推播通知讓 PWA 在使用者沒有開啟網站時,仍能由伺服器送出訊息、在系統通知列顯示提醒。它由兩個 API 組成:Push API 負責「從伺服器把訊息送到瀏覽器」,Notifications API 負責「把訊息顯示成系統通知」;中間由 Service Worker 在背景接收。本頁說明完整流程、前後端程式碼,以及 iOS 的限制。

推播通知的流程是什麼?

sequenceDiagram
    participant U as 使用者
    participant P as 網頁
    participant S as 你的伺服器
    participant B as 推播服務(瀏覽器廠商)
    participant W as Service Worker
    U->>P: 點擊「開啟通知」
    P->>U: 請求通知權限
    P->>B: subscribe()(帶 VAPID 公鑰)
    B-->>P: 回傳訂閱資訊(endpoint 與金鑰)
    P->>S: 把訂閱資訊存到資料庫
    S->>B: 用 VAPID 私鑰簽章並送出訊息
    B->>W: 喚醒 Service Worker,觸發 push 事件
    W->>U: showNotification() 顯示通知

「推播服務」由瀏覽器廠商提供(Chrome 是 Firebase Cloud Messaging、Safari 是 Apple Push Notification service、Firefox 是 Mozilla Push Service),你的伺服器只要照 Web Push 標準送到訂閱資訊裡的 endpoint 網址即可,不必分別串接各家。

什麼是 VAPID 金鑰?

VAPID(Voluntary Application Server Identification)是一組公私鑰,用來證明「這則推播確實來自訂閱時的那個伺服器」。公鑰放在前端訂閱時使用,私鑰留在伺服器簽章。可以用 web-push 套件產生:

npx web-push generate-vapid-keys

前端:請求權限並訂閱

app.js
async function enablePush() {
  const permission = await Notification.requestPermission();
  if (permission !== 'granted') return;

  const reg = await navigator.serviceWorker.ready;
  const subscription = await reg.pushManager.subscribe({
    userVisibleOnly: true,                       // 承諾每則推播都會顯示通知
    applicationServerKey: VAPID_PUBLIC_KEY,      // 公鑰字串
  });

  await fetch('/api/subscribe', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(subscription),
  });
}

document.getElementById('enable-push').addEventListener('click', enablePush);

Notification.requestPermission() 必須由使用者點擊觸發。一進站就跳權限視窗,使用者多半會拒絕,而且拒絕後網站無法再次詢問,只能請使用者到瀏覽器設定手動開啟。

Service Worker:接收並顯示通知

sw.js
self.addEventListener('push', (event) => {
  const data = event.data?.json() ?? { title: '新通知', body: '' };
  event.waitUntil(
    self.registration.showNotification(data.title, {
      body: data.body,
      icon: '/icons/icon-192.png',
      badge: '/icons/badge-72.png',
      data: { url: data.url ?? '/' },
    })
  );
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  event.waitUntil(clients.openWindow(event.notification.data.url));
});

收到 push 事件時一定要顯示通知。Chrome 會懲罰「靜默推播」,iOS Safari 甚至可能在多次未顯示後撤銷訂閱。

後端:送出推播(Node.js 範例)

server.js
import webpush from 'web-push';

webpush.setVapidDetails(
  'mailto:admin@example.com',
  process.env.VAPID_PUBLIC_KEY,
  process.env.VAPID_PRIVATE_KEY,
);

await webpush.sendNotification(subscription, JSON.stringify({
  title: '今日記帳提醒',
  body: '今天還沒記帳喔!',
  url: '/new',
}));

sendNotification 回傳 404 或 410 時代表訂閱已失效(使用者取消權限或解除安裝),應從資料庫刪除。Python、PHP、Java 等語言也有對應的 Web Push 套件。

iPhone 可以收到 PWA 推播嗎?

iPhone 與 iPad 從 iOS/iPadOS 16.4 開始支援 Web Push,但有兩個條件:

  1. 使用者必須先用 Safari 把 PWA 加入主畫面,並從主畫面開啟;在 Safari 分頁中無法訂閱推播。
  2. Manifest 的 display 必須是 standalone 或 fullscreen。

因此在 iOS 上的推播流程,應該先引導安裝(見 安裝體驗),安裝後再顯示「開啟通知」按鈕。

使用推播的良好習慣

  • 讓使用者知道會收到什麼:在請求權限前說明「訂單出貨時通知你」,比空泛的「開啟通知」轉換率高很多。
  • 少而精:只送和使用者直接相關、有時效性的訊息。
  • 提供關閉入口:在 App 設定中讓使用者可以取消訂閱(subscription.unsubscribe())。

相關資料