ServiceWorkerGlobalScope: sự kiện push

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2023.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Note: This feature is only available in Service Workers.

Sự kiện push được gửi đến phạm vi toàn cục của service worker (đại diện bởi giao diện ServiceWorkerGlobalScope) khi service worker đã nhận được một thông báo đẩy.

Sự kiện này không thể hủy và không nổi bọt.

Cú pháp

Sử dụng tên sự kiện trong các phương thức như addEventListener(), hoặc thiết lập một thuộc tính trình xử lý sự kiện.

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

onpush = (event) => { }

Loại sự kiện

Một PushEvent. Kế thừa từ Event.

Event ExtendableEvent PushEvent

Thuộc tính sự kiện

Kế thừa các thuộc tính từ giao diện cha, ExtendableEvent. Các thuộc tính bổ sung:

PushEvent.data Read only

Trả về một tham chiếu đến đối tượng PushMessageData chứa dữ liệu được gửi đến PushSubscription.

Ví dụ

Ví dụ này thiết lập một trình xử lý cho các sự kiện push lấy dữ liệu JSON, phân tích cú pháp nó, và phân phối thông điệp để xử lý dựa trên thông tin contained trong thông điệp.

js
self.addEventListener("push", (event) => {
  let message = event.data.json();

  switch (message.type) {
    case "init":
      doInit();
      break;
    case "shutdown":
      doShutdown();
      break;
  }
});

Đặc tả kỹ thuật

Specification
Push API
# extensions-to-the-serviceworkerglobalscope-interface
Push API
# dom-serviceworkerglobalscope-onpush

Tương thích trình duyệt

Xem thêm