{{APIRef("Websockets API")}}
The EventSource
interface is used to receive server-sent events. It connects to a server over HTTP and receives events in text/event-stream
format without closing the connection.
You can set the onmessage
attribute to a JavaScript function to receive non-typed messages (that is, messages with no event
field). You can also call addEventListener()
to listen for events just like any other EventTarget
.
See Using server-sent events for further details.
Methods
- {{domxref("EventSource.close()")}}
- Closes the connection, if any, and sets the
readyState
attribute toCLOSED
. If the connection is already closed, the method does nothing.
Properties
- {{domxref("EventSource.onerror")}}
- Is an {{domxref("EventHandler")}} being called when an error occurs and the {{event("error")}} event is dispatched on this object.
- {{domxref("EventSource.onmessage")}}
- Is an {{domxref("EventHandler")}} being called when a {{event("message")}} event is received, that is when a message is coming from the source.
- {{domxref("EventSource.onopen")}}
- Is an {{domxref("EventHandler")}} being called when an {{event("open")}} event is received, that is when the connection was just opened.
- {{domxref("EventSource.readyState")}} {{readonlyinline}}
- An
unsigned short
representing the state of the connection. Possible values areCONNECTING
(0
),OPEN
(1
), orCLOSED
(2
). - {{domxref("EventSource.url")}} {{readonlyinline}}
- A {{domxref("DOMString")}} representing the URL of the source.
Specifications
{{ spec("https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface","Server-Sent Events: The EventSource Interface","CR") }}
Browser compatibility
{{ CompatibilityTable() }}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 9 | {{ CompatGeckoDesktop("6.0") }} | {{ CompatUnknown() }} | 11 | 5 |
CORS support | 26 | {{ CompatGeckoDesktop("11.0") }} | {{ CompatUnknown() }} | 12 | {{ CompatUnknown() }} |
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | {{ CompatAndroid("4.4") }} | {{ CompatUnknown() }} | {{CompatUnknown()}} | {{ CompatUnknown() }} | {{ CompatUnknown() }} |