ExtendableMessageEvent: data property

Baseline Widely available

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

Note: This feature is only available in Service Workers.

Thuộc tính chỉ đọc data của giao diện ExtendableMessageEvent trả về dữ liệu của sự kiện. Có thể là bất kỳ loại dữ liệu nào.

Giá trị

Bất kỳ loại dữ liệu nào.

Ví dụ

Khi đoạn mã dưới đây được dùng trong service worker để phản hồi các thông báo push bằng cách gửi dữ liệu nhận qua PushMessageData đến ngữ cảnh chính qua channel message, đối tượng sự kiện của onmessage sẽ là ExtendableMessageEvent.

js
let port;

self.addEventListener("push", (e) => {
  const obj = e.data.json();

  if (obj.action === "subscribe" || obj.action === "unsubscribe") {
    port.postMessage(obj);
  } else if (obj.action === "init" || obj.action === "chatMsg") {
    port.postMessage(obj);
  }
});

self.onmessage = (e) => {
  console.log(e.data);
  port = e.ports[0];
};

Thông số kỹ thuật

Specification
Service Workers Nightly
# extendablemessage-event-data

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

Xem thêm