MessageChannel
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.
Note: This feature is available in Web Workers.
Giao diện MessageChannel của Channel Messaging API cho phép tạo một kênh tin nhắn mới và gửi dữ liệu qua đó thông qua hai thuộc tính MessagePort.
Hàm khởi tạo
MessageChannel()-
Trả về một đối tượng
MessageChannelmới với hai đối tượngMessagePortmới.
Thuộc tính phiên bản
MessageChannel.port1Read only-
Trả về port1 của kênh.
MessageChannel.port2Read only-
Trả về port2 của kênh.
Ví dụ
Trong ví dụ sau, bạn có thể thấy một kênh mới được tạo bằng hàm khởi tạo MessageChannel().
Khi IFrame đã tải, chúng ta đăng ký một trình xử lý onmessage cho MessageChannel.port1 và chuyển MessageChannel.port2 đến IFrame bằng phương thức window.postMessage cùng với một tin nhắn.
Khi nhận được tin nhắn phản hồi từ IFrame, hàm onMessage hiển thị tin nhắn vào một đoạn văn.
const channel = new MessageChannel();
const output = document.querySelector(".output");
const iframe = document.querySelector("iframe");
// Wait for the iframe to load
iframe.addEventListener("load", onLoad);
function onLoad() {
// Listen for messages on port1
channel.port1.onmessage = onMessage;
// Transfer port2 to the iframe
iframe.contentWindow.postMessage("Hello from the main page!", "*", [
channel.port2,
]);
}
// Handle messages received on port1
function onMessage(e) {
output.innerHTML = e.data;
}
Để xem ví dụ đầy đủ, hãy xem channel messaging basic demo trên GitHub (chạy trực tiếp).
Thông số kỹ thuật
| Specification |
|---|
| HTML> # message-channels> |