--- title: EventSource slug: Web/API/EventSource tags: - API - Communications - EventSource - Interface - NeedsTranslation - Reference - Server Sent Events - Server-sent events - TopicStub - messaging translation_of: Web/API/EventSource ---
The EventSource
interface is web content's interface to server-sent events. An EventSource
instance opens a persistent connection to an HTTP server, which sends events in text/event-stream
format. The connection remains open until closed by calling {{domxref("EventSource.close()")}}.
Once the connection is opened, incoming messages from the server are delivered to your code in the form of {{event("message")}} events.
Unlike WebSockets, server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). That makes them an excellent choice when there's no need to send data from the client to the server in message form. For example, EventSource
is a useful approach for handling things like social media status updates, news feeds, or delivering data into a client-side storage mechanism like IndexedDB or web storage.
EventSource
to handle receiving server-sent events from a specified URL, optionally in credentials mode.This interface also inherits properties from its parent, {{domxref("EventTarget")}}.
CONNECTING
(0
), OPEN
(1
), or CLOSED
(2
).EventSource
object was instantiated with cross-origin (CORS) credentials set (true
), or not (false
, the default).EventSource
object.This interface also inherits methods from its parent, {{domxref("EventTarget")}}.
readyState
attribute to CLOSED
. If the connection is already closed, the method does nothing.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.
var evtSource = new EventSource('sse.php'); var eventList = document.querySelector('ul'); evtSource.onmessage = function(e) { var newElement = document.createElement("li"); newElement.textContent = "message: " + e.data; eventList.appendChild(newElement); }
Each received event causes our EventSource
object's onmessage
event handler to be run. It, in turn, creates a new {{HTMLElement("li")}} element and writes the message's data into it, then appends the new element to the list element already in the document.
Note: You can find a full example on GitHub — see Simple SSE demo using PHP.
Specification | Status |
---|---|
{{SpecName('HTML WHATWG', "comms.html#the-eventsource-interface", "EventSource")}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.EventSource")}}