通知行为

Alexey Rodionov
Alexey Rodionov
Matt Gaunt

到目前为止,我们已经了解了更改通知视觉外观的选项。还有一些选项可以改变通知的行为。

默认情况下,仅使用视觉选项调用 showNotification() 具有以下行为:

  • 点击通知不会执行任何操作。
  • 每条新通知会一个接一个地显示。浏览器不会以任何方式收起通知。
  • 平台可能会播放声音或振动用户的设备(具体取决于平台)。
  • 在某些平台上,通知会在不久后消失,而另一些平台则会显示通知,除非用户与之互动。(例如,比较 Android 和桌面设备上的通知。)

在本部分中,我们将了解如何仅使用选项来更改这些默认行为。这些 API 相对容易实现和利用。

通知点击事件

当用户点击通知时,默认行为是没有任何反应。甚至不会关闭或移除通知。

通知点击的常见做法是关闭并执行一些其他逻辑(例如打开一个窗口或对应用进行某些 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() 方法并执行额外的工作。

Action

借助操作,您可以与用户进行更高层次的互动,而不只是点击通知。

按钮

在上一部分中,您了解了在调用 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);

现在,即使调用了 3 次 showNotification(),我们也有两条通知。

两条通知,其中第一条通知替换为第三条通知。

tag 选项只是一种对消息进行分组的方法,这样一来,如果当前显示的任何旧通知与新通知的标签相同,系统就会关闭这些通知。

使用 tag 的一个小技巧是,当它替换通知时,不会发出提示音或振动。

这正是 renotify 选项的用武之地。

重新通知

在撰写本文时,这在很大程度上适用于移动设备。设置此选项会使新通知振动并播放系统声音。

在某些情况下,您可能希望替换通知来通知用户,而不是静默更新。聊天应用就是一个很好的例子。在这种情况下,您应将 tagrenotify 设置为 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);

使用此选项时请慎重考虑。如果显示通知并强制用户停止正在执行的操作以关闭通知,可能会令人沮丧。

在下一部分,我们将了解网页上用于管理通知和执行点击通知时打开页面等操作的一些常用模式。

下一步做什么

Codelab