程式碼研究室:建構推播通知用戶端

凱特傑瑞斯
Kate Jeffreys

本程式碼研究室會逐步說明如何建構推播通知用戶端。完成程式碼研究室後,您的用戶端會:

  • 讓使用者訂閱推播通知。
  • 接收推送訊息,並以通知形式顯示。
  • 為使用者取消訂閱推播通知。

本程式碼研究室的重點在於幫助您透過實踐方式學習,並且不會深入談論概念。如要瞭解推播通知的概念,請參閱推播通知的運作方式?一文。

本程式碼研究室的伺服器程式碼已經完成。您只需在本程式碼研究室中實作用戶端。如要瞭解如何實作推播通知伺服器,請參閱「程式碼研究室:建構推播通知伺服器」。

請參閱 push-notifications-client-codelab-complete (來源),查看完整的程式碼。

瀏覽器相容性

本程式碼研究室已知會使用下列作業系統和瀏覽器組合:

  • Windows:Chrome、Edge
  • macOS:Chrome、Firefox
  • Android:Chrome、Firefox

本程式碼研究室已知「無法」與下列作業系統 (或作業系統和瀏覽器組合) 搭配使用:

  • macOS:Brave、Edge、Safari
  • iOS

設定

取得可編輯的程式碼副本

這些操作說明右側的程式碼編輯器在本程式碼研究室中將稱為「Glitch UI」。

  1. 按一下「Remix to Edit」,讓專案可供編輯。

設定驗證方法

您需要使用驗證金鑰設定伺服器和用戶端,才能讓推播通知正常運作。如要瞭解原因,請參閱「簽署網路推送通訊協定要求」。

  1. 在 Glitch UI 中,依序按一下「工具」和「終端機」,開啟 Glitch 終端機。
  2. 在 Glitch 終端機中執行 npx web-push generate-vapid-keys。請複製私密金鑰和公開金鑰值。
  3. 在 Glitch UI 中開啟 .env,並更新 VAPID_PUBLIC_KEYVAPID_PRIVATE_KEY。將 VAPID_SUBJECT 設為 mailto:test@test.test。所有這些值都應該以雙引號括住。更新完成後,.env 檔案應如下所示:
VAPID_PUBLIC_KEY="BKiwTvD9HA…"
VAPID_PRIVATE_KEY="4mXG9jBUaU…"
VAPID_SUBJECT="mailto:test@test.test"
  1. 關閉 Glitch 終端機。
  1. 開啟 public/index.js
  2. VAPID_PUBLIC_KEY_VALUE_HERE 替換成公開金鑰的值。

註冊 Service Worker

您的用戶端最終需要 Service Worker 來接收和顯示通知。建議您盡早註冊 Service Worker。 詳情請參閱「以通知的形式接收和顯示已推送的訊息」。

  1. // TODO add startup logic here 註解替換為下列程式碼:
// TODO add startup logic here
if ('serviceWorker' in navigator && 'PushManager' in window) {
  navigator.serviceWorker.register('./service-worker.js').then(serviceWorkerRegistration => {
    console.info('Service worker was registered.');
    console.info({serviceWorkerRegistration});
  }).catch(error => {
    console.error('An error occurred while registering the service worker.');
    console.error(error);
  });
  subscribeButton.disabled = false;
} else {
  console.error('Browser does not support service workers or push messages.');
}

subscribeButton.addEventListener('click', subscribeButtonHandler);
unsubscribeButton.addEventListener('click', unsubscribeButtonHandler);
  1. 如要預覽網站,請按下「查看應用程式」,然後按下「全螢幕」圖示 全螢幕
  1. 按下 `Control+Shift+J 鍵 (在 Mac 上為 Command+Option+J 鍵) 開啟開發人員工具。
  2. 再按一下 [Console] (控制台) 標籤即可。您應該可以在控制台中看到 Service worker was registered. 的訊息。

要求推播通知權限

請勿在載入網頁時要求傳送推播通知的權限。 相反地,使用者介面應詢問使用者是否要接收推播通知。等到他們明確確認 (例如點選按鈕) 後,您就可以開始正式程序,從瀏覽器取得推播通知權限。

  1. 在 Glitch UI 中,按一下「View Source」,返回程式碼。
  2. public/index.js 中,將 subscribeButtonHandler() 中的 // TODO 註解替換為以下程式碼:
// TODO
// Prevent the user from clicking the subscribe button multiple times.
subscribeButton.disabled = true;
const result = await Notification.requestPermission();
if (result === 'denied') {
  console.error('The user explicitly denied the permission request.');
  return;
}
if (result === 'granted') {
  console.info('The user accepted the permission request.');
}
  1. 返回應用程式分頁,然後按一下「訂閱推送」。瀏覽器或作業系統可能會詢問您是否要讓網站傳送推播通知。按一下「Allow」(允許) (或您瀏覽器/OS 使用的對等詞組)。您應該會在主控台中看到接受或拒絕要求的訊息。

訂閱推播通知

訂閱程序涉及與瀏覽器廠商控管的網路服務互動,稱為「推送服務」。取得推播通知訂閱資訊後,您必須將該資訊傳送至伺服器,並由伺服器長期將其儲存在資料庫中。如要進一步瞭解訂閱程序,請參閱「訂閱用戶端以推送通知」。

  1. 將以下醒目顯示的程式碼加入 subscribeButtonHandler()
subscribeButton.disabled = true;
const result = await Notification.requestPermission();
if (result === 'denied') {
  console.error('The user explicitly denied the permission request.');
  return;
}
if (result === 'granted') {
  console.info('The user accepted the permission request.');
}
const registration = await navigator.serviceWorker.getRegistration();
const subscribed = await registration.pushManager.getSubscription();
if (subscribed) {
  console.info('User is already subscribed.');
  notifyMeButton.disabled = false;
  unsubscribeButton.disabled = false;
  return;
}
const subscription = await registration.pushManager.subscribe({
  userVisibleOnly: true,
  applicationServerKey: urlB64ToUint8Array(VAPID_PUBLIC_KEY)
});
notifyMeButton.disabled = false;
fetch('/add-subscription', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(subscription)
});

userVisibleOnly 選項必須為 true。一天或許可以在不顯示使用者可見通知的情況下推送訊息 (靜音推送),但瀏覽器目前基於隱私權考量,不允許這項功能。

applicationServerKey 值仰賴公用函式,可將 Base64 字串轉換為 Uint8Array。這個值用於伺服器和推送服務之間的驗證。

取消訂閱推播通知

使用者訂閱推播通知後,您的 UI 需要提供取消訂閱的方法,以防使用者改變心意且不想繼續接收推播通知。

  1. unsubscribeButtonHandler() 中的 // TODO 註解替換為下列程式碼:
// TODO
const registration = await navigator.serviceWorker.getRegistration();
const subscription = await registration.pushManager.getSubscription();
fetch('/remove-subscription', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({endpoint: subscription.endpoint})
});
const unsubscribed = await subscription.unsubscribe();
if (unsubscribed) {
  console.info('Successfully unsubscribed from push notifications.');
  unsubscribeButton.disabled = true;
  subscribeButton.disabled = false;
  notifyMeButton.disabled = true;
}

接收推送訊息,並以通知形式顯示

如前所述,對於從您的伺服器推送至用戶端的訊息,您需要服務工作站來處理相關接收與顯示訊息。詳情請參閱「以通知的形式接收和顯示已推送的訊息」。

  1. 開啟 public/service-worker.js,然後將 Service Worker 的 push 事件處理常式中的 // TODO 註解替換為下列程式碼:
// TODO
let data = event.data.json();
const image = 'https://cdn.glitch.com/614286c9-b4fc-4303-a6a9-a4cef0601b74%2Flogo.png?v=1605150951230';
const options = {
  body: data.options.body,
  icon: image
}
self.registration.showNotification(
  data.title, 
  options
);
  1. 返回應用程式分頁。
  2. 按一下「通知我」。您應該會收到推播通知。
  3. 請嘗試在其他瀏覽器 (或其他裝置) 中開啟應用程式分頁的網址,完成訂閱工作流程,然後按一下「Notify all」。您應會在所有已訂閱的瀏覽器上收到相同的推播通知。請參閱「瀏覽器相容性」一節,查看已知是否能運作或無法運作的瀏覽器/OS 組合清單。

您可以透過多種方式自訂通知。詳情請參閱 ServiceWorkerRegistration.showNotification() 的參數。

使用者點擊通知時開啟網址

實際上,您可能會利用通知,再次吸引使用者造訪您的網站。為此,您必須進一步設定 Service Worker。

  1. 使用下列程式碼,取代 Service Worker 的 notificationclick 事件處理常式中的 // TODO 註解:
// TODO
event.notification.close();
event.waitUntil(self.clients.openWindow('https://web.dev'));
  1. 請返回應用程式分頁,再次傳送通知,然後按一下通知。瀏覽器應該會開啟新分頁並載入 https://web.dev

後續步驟