BroadcastChannel: message event - Web APIs 编辑

The message event is fired on a BroadcastChannel object when a message arrives on that channel.

BubblesNo
CancelableNo
InterfaceMessageEvent
Event handler propertyonmessage

Examples

Live example

In this example there's a "sender" <iframe> that broadcasts the contents of a <textarea> when the user clicks a button. There are two "receiver" iframes that listen to the broadcast message and write the result into a <div> element.

Sender

<h1>Sender</h1>
<label for="message">Type a message to broadcast:</label><br/>
<textarea id="message" name="message" rows="1" cols="40">Hello</textarea>
<button id="broadcast-message" type="button">Broadcast message</button>
body {
     border: 1px solid black;
     padding: .5rem;
     height: 150px;
     font-family: "Fira Sans", sans-serif;
}

h1 {
    font: 1.6em "Fira Sans", sans-serif;
    margin-bottom: 1rem;
}

textarea {
    padding: .2rem;
}

label, br {
    margin: .5rem 0;
}

button {
    vertical-align: top;
    height: 1.5rem;
}
const channel = new BroadcastChannel('example-channel');
const messageControl = document.querySelector('#message');
const broadcastMessageButton = document.querySelector('#broadcast-message');

broadcastMessageButton.addEventListener('click', () => {
    channel.postMessage(messageControl.value);
})

Receiver 1

<h1>Receiver 1</h1>
<div id="received"></div>
body {
    border: 1px solid black;
    padding: .5rem;
    height: 100px;
    font-family: "Fira Sans", sans-serif;
}

h1 {
    font: 1.6em "Fira Sans",
    sans-serif; margin-bottom: 1rem;
}
const channel = new BroadcastChannel('example-channel');
channel.addEventListener('message', (event) => {
  received.textContent = event.data;
});

Receiver 2

<h1>Receiver 2</h1>
<div id="received"></div>
body {
    border: 1px solid black;
    padding: .5rem;
    height: 100px;
    font-family: "Fira Sans", sans-serif;
}

h1 {
    font: 1.6em "Fira Sans", sans-serif;
    margin-bottom: 1rem;
}
const channel = new BroadcastChannel('example-channel');
channel.addEventListener('message', (event) => {
  received.textContent = event.data;
});

Result

Specifications

SpecificationStatus
HTML Living StandardLiving Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:78 次

字数:5658

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文