EventSource: message event
MDN Web Docs · نسخهٔ df622a2a1c1e · CC BY-SA 2.5 و مجوز جداگانهٔ ناشر برای نمونهکد
{{APIRef("Server Sent Events")}}{{AvailableInWorkers}}
The **message** event of the {{domxref("EventSource")}} interface is fired when data is received through an event source.
This event is not cancelable and does not bubble.
Syntax
Use the event name in {{domxref("EventTarget/addEventListener", "addEventListener()")}}:
addEventListener("message", (event) => { })Alternatively, assign to the event handler property of the interface:
onmessage = (event) => { }Event type
A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("MessageEvent")}}
Examples
In this basic example, an EventSource is created to receive events from the server; a page with the name sse.php is responsible for generating the events.
const evtSource = new EventSource("sse.php");
const eventList = document.querySelector("ul");
evtSource.addEventListener("message", (e) => {
const newElement = document.createElement("li");
newElement.textContent = `message: ${e.data}`;
eventList.appendChild(newElement);
});Using the onmessage event handler property
You can also use the onmessage event handler property (but note that this replaces other event listeners added using onmessage, if any):
evtSource.onmessage = (e) => {
const newElement = document.createElement("li");
newElement.textContent = `message: ${e.data}`;
eventList.appendChild(newElement);
};Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
- Using server-sent events
- [
open](/en-US/docs/Web/API/EventSource/open_event) - [
error](/en-US/docs/Web/API/EventSource/error_event)