--- title: 'WebSocket: message event' slug: Web/API/WebSocket/message_event translation_of: Web/API/WebSocket/message_event --- <div> <p>{{APIRef}}</p> <p><code>message</code> 事件会在 <code>WebSocket</code> 接收到新消息时被触发。</p> <table> <tbody> <tr> <th scope="row">起泡(Bubbles)</th> <td>不</td> </tr> <tr> <th scope="row">可取消</th> <td>不</td> </tr> <tr> <th scope="row">接口</th> <td>{{domxref("MessageEvent")}}</td> </tr> <tr> <th scope="row">事件处理程序属性</th> <td>{{ domxref("WebSocket.onmessage","onmessage")}}</td> </tr> </tbody> </table> <h2 id="例子">例子</h2> <pre>// 创建一个 WebSocket 连接 const socket = new WebSocket('ws://localhost:8080'); // 监听消息 socket.addEventListener('message', function (event) { console.log('Message from server ', event.data); });</pre> <h2 id="规范">规范</h2> <table> <thead> <tr> <th>规范</th> <th>状态</th> </tr> </thead> <tbody> <tr> <td>{{SpecName("HTML WHATWG", "web-sockets.html#event-message", "WebSocket message")}}</td> <td>{{Spec2("HTML WHATWG")}}</td> </tr> </tbody> </table> <h2 id="浏览器兼容性">浏览器兼容性</h2> <p>{{Compat("api.WebSocket.message_event")}}</p> <h2 id="另看">另看</h2> <ul> <li><a href="/en-US/docs/Web/API/WebSocket/close_event">WebSocket: close event</a></li> <li><a href="/en-US/docs/Web/API/WebSocket/error_event">WebSocket: error event</a></li> <li><a href="/en-US/docs/Web/API/WebSocket/open_event">WebSocket: open event</a></li> <li><a href="/en-US/docs/WebSockets/Writing_WebSocket_client_applications">Writing WebSocket client applications</a></li> <li></li> </ul> </div> <ul> <li></li> </ul>