通知行為

Alexey Rodionov
Alexey Rodionov
Matt Gaunt

到目前為止,我們已探討過可改變通知外觀的選項。此外,您也可以使用其他選項來變更通知行為。

根據預設,只使用視覺選項呼叫 showNotification() 時,會出現下列行為:

  • 點選通知不會有任何反應。
  • 每則新通知會依序顯示。瀏覽器不會以任何方式收合通知。
  • 平台可能會播放音效或震動使用者的裝置 (視平台而定)。
  • 在某些平台上,通知會在短時間內消失,而其他平台則會顯示通知,直到使用者與通知互動為止。(例如比較 Android 和電腦上的通知)。

在本節中,我們將探討如何單獨使用選項來變更這些預設行為。這些做法相對容易實作,且能帶來好處。

通知點擊事件

使用者點選通知時,預設行為是不會發生任何事。甚至不會關閉或移除通知。

點選通知的常見做法是關閉通知並執行其他邏輯 (例如開啟視窗或對應用程式發出 API 呼叫)。

為此,您需要在 Service Worker 中新增 'notificationclick' 事件監聽器。每當使用者點選通知時,系統就會呼叫這個函式。

self.addEventListener('notificationclick', (event) => {
  const clickedNotification = event.notification;
  clickedNotification.close();

  // Do something as the result of the notification click
  const promiseChain = doSomething();
  event.waitUntil(promiseChain);
});

如這個範例所示,使用者點擊的通知可透過 event.notification 存取。您可以透過這個物件存取通知的屬性和方法。在這種情況下,您會呼叫其 close() 方法並執行其他工作。

動作

除了點擊通知外,動作還能讓您與使用者進行另一層互動。

按鈕

上一節說明瞭如何在呼叫 showNotification() 時定義動作按鈕:

const title = 'Actions Notification';

const options = {
  actions: [
    {
      action: 'coffee-action',
      title: 'Coffee',
      type: 'button',
      icon: '/images/demos/action-1-128x128.png',
    },
    {
      action: 'doughnut-action',
      type: 'button',
      title: 'Doughnut',
      icon: '/images/demos/action-2-128x128.png',
    },
    {
      action: 'gramophone-action',
      type: 'button',
      title: 'Gramophone',
      icon: '/images/demos/action-3-128x128.png',
    },
    {
      action: 'atom-action',
      type: 'button',
      title: 'Atom',
      icon: '/images/demos/action-4-128x128.png',
    },
  ],
};

registration.showNotification(title, options);

如果使用者點選動作按鈕,請檢查 noticationclick 事件中的 event.action 值,判斷使用者點選了哪個動作按鈕。

event.action 將包含選項中設定的 action 值。在上述範例中,event.action 值會是下列其中一項:'coffee-action'、'doughnut-action'、'gramophone-action' 或 'atom-action'。

這樣一來,我們就能偵測通知點擊或動作點擊,如下所示:

self.addEventListener('notificationclick', (event) => {
  if (!event.action) {
    // Was a normal notification click
    console.log('Notification Click.');
    return;
  }

  switch (event.action) {
    case 'coffee-action':
      console.log("User ❤️️'s coffee.");
      break;
    case 'doughnut-action':
      console.log("User ❤️️'s doughnuts.");
      break;
    case 'gramophone-action':
      console.log("User ❤️️'s music.");
      break;
    case 'atom-action':
      console.log("User ❤️️'s science.");
      break;
    default:
      console.log(`Unknown action clicked: '${event.action}'`);
      break;
  }
});

內嵌回覆

此外,在上一節中,您已瞭解如何將內嵌回覆新增至通知:

const title = 'Poll';

const options = {
  body: 'Do you like this photo?',
  image: '/images/demos/cat-image.jpg',
  icon: '/images/demos/icon-512x512.png',
  badge: '/images/demos/badge-128x128.png',
  actions: [
    {
      action: 'yes',
      type: 'button',
      title: '👍 Yes',
    },
    {
      action: 'no',
      type: 'text',
      title: '👎 No (explain why)',
      placeholder: 'Type your explanation here',
    },
  ],
};

registration.showNotification(title, options);

event.reply 會包含使用者在輸入欄位中輸入的值:

self.addEventListener('notificationclick', (event) => {
  const reply = event.reply;

  // Do something with the user's reply
  const promiseChain = doSomething(reply);
  event.waitUntil(promiseChain);
});

標記

tag 選項基本上是將通知「分組」在一起的字串 ID,可讓您輕鬆決定如何向使用者顯示多則通知。我們用一個例子來說明。

我們來顯示通知,並加上 'message-group-1' 標記。我們會使用以下程式碼顯示通知:

const title = 'Notification 1 of 3';

const options = {
  body: "With 'tag' of 'message-group-1'",
  tag: 'message-group-1',
};

registration.showNotification(title, options);

這會顯示第一個通知。

第一則通知,標記為訊息群組 1。

讓我們顯示第二個通知,並加上 'message-group-2' 的新標記,如下所示:

const title = 'Notification 2 of 3';

const options = {
  body: "With 'tag' of 'message-group-2'",
  tag: 'message-group-2',
};

registration.showNotification(title, options);

系統會向使用者顯示第二則通知。

兩則通知,其中第二則通知為訊息群組 2 的第二個標記。

現在,我們來顯示第三則通知,但重複使用 'message-group-1' 的第一個標記。這樣做會關閉第一則通知,並以新通知取代。

const title = 'Notification 3 of 3';

const options = {
  body: "With 'tag' of 'message-group-1'",
  tag: 'message-group-1',
};

registration.showNotification(title, options);

現在,即使 showNotification() 呼叫了三次,我們也只會收到兩則通知。

兩則通知,其中第一則通知由第三則通知取代。

tag 選項只是將訊息分組的一種方式,因此如果目前顯示的任何舊通知與新通知具有相同的標記,系統就會關閉這些舊通知。

使用 tag 的細微之處在於,當它取代通知時,會「不」發出聲音或震動。

這時 renotify 選項就能派上用場。

重新通知

目前這項功能主要適用於行動裝置。設定這個選項後,新通知會震動並播放系統音效。

在某些情況下,您可能希望取代通知能通知使用者,而不是在背景更新。聊天應用程式就是一個很好的例子。在這種情況下,您應將 tag 和 renotify 設為 true。

const title = 'Notification 2 of 2';

const options = {
  tag: 'renotify',
  renotify: true,
};

registration.showNotification(title, options);

靜音

這個選項可讓您顯示新通知,但會防止震動、音效和開啟裝置螢幕等預設行為。

若通知不需要使用者立即處理,就很適合採用這種做法。

const title = 'Silent Notification';

const options = {
  silent: true,
};

registration.showNotification(title, options);

需要互動

電腦版 Chrome 會在設定的時間範圍內顯示通知,然後隱藏。Android 版 Chrome 沒有這種行為。通知會持續顯示,直到使用者與其互動為止。

如要強制通知持續顯示,直到使用者與通知互動為止,請新增 requireInteraction 選項。這樣一來,系統就會持續顯示通知,直到使用者關閉或點選通知為止。

const title = 'Require Interaction Notification';

const options = {
  requireInteraction: true,
};

registration.showNotification(title, options);

請謹慎使用這個選項。如果顯示通知,並強迫使用者停止正在進行的操作,才能關閉通知,可能會讓使用者感到不悅。

在下一節中,我們將介紹網路上常見的通知管理模式,以及點選通知時開啟網頁等動作。

後續步驟

程式碼研究室