ServiceWorkerGlobalScope: notificationclick 事件

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

注意:此功能仅在 Service Workers 中可用。

notificationclick 事件是 ServiceWorkerGlobalScope 接口的一个事件,当通过 ServiceWorkerRegistration.showNotification() 触发的系统通知被点击时,会触发该事件。

在主线程或非 Service Worker 的 worker 中使用 Notification() 构造函数创建的通知,将在 Notification 对象本身上收到一个 click 事件。

此事件不可取消,也不会冒泡。

语法

在诸如 addEventListener() 之类的方法中使用事件名称,或设置事件处理程序属性。

js
addEventListener("notificationclick", (event) => { })

onnotificationclick = (event) => { }

事件类型

这是一个 NotificationEvent。继承自 ExtendableEventEvent

Event ExtendableEvent NotificationEvent

事件属性

继承自其祖先 ExtendableEventEvent 的属性。.

NotificationEvent.notification 只读

返回一个 Notification 对象,表示被点击以触发事件的通知。

NotificationEvent.action 只读

返回用户点击的通知按钮的字符串 ID。如果用户点击了通知中的操作按钮以外的区域,或者通知没有按钮,则此值为空字符串。

示例

您可以在 addEventListener 方法中使用 notificationclick 事件。

js
self.addEventListener("notificationclick", (event) => {
  console.log("On notification click: ", event.notification.tag);
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(
    clients
      .matchAll({
        type: "window",
      })
      .then((clientList) => {
        for (const client of clientList) {
          if (client.url === "/" && "focus" in client) return client.focus();
        }
        if (clients.openWindow) return clients.openWindow("/");
      }),
  );
});

或者使用 onnotificationclick 事件处理程序属性。

js
self.onnotificationclick = (event) => {
  console.log("On notification click: ", event.notification.tag);
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(
    clients
      .matchAll({
        type: "window",
      })
      .then((clientList) => {
        for (const client of clientList) {
          if (client.url === "/" && "focus" in client) return client.focus();
        }
        if (clients.openWindow) return clients.openWindow("/");
      }),
  );
};

您可以在 notificationclick 事件处理程序中使用 event.action 来处理事件操作。

js
navigator.serviceWorker.register("sw.js");
Notification.requestPermission().then((result) => {
  if (result === "granted") {
    navigator.serviceWorker.ready.then((registration) => {
      // Show a notification that includes an action titled Archive.
      registration.showNotification("New mail from Alice", {
        actions: [
          {
            action: "archive",
            title: "Archive",
          },
        ],
      });
    });
  }
});

self.addEventListener("notificationclick", (event) => {
  event.notification.close();
  if (event.action === "archive") {
    // User selected the Archive action.
    archiveEmail();
  } else {
    // User selected (e.g., clicked in) the main body of notification.
    clients.openWindow("/inbox");
  }
});

规范

规范
Notifications API
# 激活通知
Notifications API
# dom-serviceworkerglobalscope-onnotificationclick

浏览器兼容性

另见