--- title: 'BroadcastChannel: message event' slug: Web/Events/message tags: - 事件 - 消息 - 通信 translation_of: Web/API/BroadcastChannel/message_event ---
当频道收到一条消息时,会在关联的 {{domxref('BroadcastChannel')}} 对象上触发 message
事件。
Bubbles | No |
---|---|
Cancelable | No |
Interface | {{domxref("MessageEvent")}} |
Event handler property | onmessage |
在这个例子中,有一个 <iframe>
作为发送者,当用户点击按钮之后,会广播 <textarea>
中的内容。同时,有两个 <iframe>
作为接收者,会监听广播的消息,并将结果写入 <div>
元素。
<h1>发送者</h1> <label for="message">输入要广播的信息:</label><br/> <textarea id="message" name="message" rows="1" cols="40">Hello</textarea> <button id="broadcast-message" type="button">开始广播</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); })
<h1>接收者 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; });
<h1>接收者 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; });
{{ EmbedLiveSample('发送者', '100%', '170px','' ,'' , 'dummy') }}
{{ EmbedLiveSample('接收者_1', '100%', '150px','' ,'' , 'dummy') }}
{{ EmbedLiveSample('接收者_2', '100%', '150px','' ,'' , 'dummy') }}
规范 | 状态 |
---|---|
{{SpecName('HTML WHATWG', 'indices.html#event-message')}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.BroadcastChannel.message_event")}}
messageerror