Firefox Tomorrow

web api event

EventSource: message event

View on MDN ↗

Available in 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 methods like addEventListener(), or set an event handler property.

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

onmessage = (event) => { }

Event type

A MessageEvent. Inherits from Event.

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);
});

onmessage equivalent

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

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

Specifications

SpecificationsStandards references are available on the canonical MDN page.

Browser compatibility

Browser compatibilityCompatibility data is available on the canonical MDN page.

See also