EventSource: message event

Baseline
Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

Note: This feature is available in Web Workers.

The message event of the 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 addEventListener():

js
addEventListener("message", (event) => { })

Alternatively, assign to the event handler property of the interface:

js
onmessage = (event) => { }

Event type

A MessageEvent. Inherits from Event.

Event 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.

js
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):

js
evtSource.onmessage = (e) => {
  const newElement = document.createElement("li");

  newElement.textContent = `message: ${e.data}`;
  eventList.appendChild(newElement);
};

Specifications

Specification
HTML
# event-message
HTML
# handler-eventsource-onmessage

Browser compatibility

See also