Constructor
EventSource()-
Creates a new
EventSourceto handle receiving server-sent events from a specified URL, optionally in credentials mode.
Instance properties
This interface also inherits properties from its parent, EventTarget.
EventSource.readyStateRead only-
A number representing the state of the connection. Possible values are
CONNECTING(0),OPEN(1), orCLOSED(2). EventSource.urlRead only-
A string representing the URL of the source.
EventSource.withCredentialsRead only-
A boolean value indicating whether the
EventSourceobject was instantiated with cross-origin (CORS) credentials set (true), or not (false, the default).
Instance methods
This interface also inherits methods from its parent, EventTarget.
EventSource.close()-
Closes the connection, if any, and sets the
readyStateattribute toCLOSED. If the connection is already closed, the method does nothing.
Events
error-
Fired when a connection to an event source failed to open.
message-
Fired when data is received from an event source.
open-
Fired when a connection to an event source has opened.
Additionally, the event source itself may send messages with an event field, which will create ad hoc events keyed to that value.
Examples
In this basic example, an EventSource is created to receive unnamed 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.onmessage = (e) => {
const 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 <li> element and writes the message's data into it, then appends the new element to the list element already in the document.
To listen to named events, you'll require a listener for each type of event sent.
js
const sse = new EventSource("/api/v1/sse");
/*
* This will listen only for events
* similar to the following:
*
* event: notice
* data: useful data
* id: some-id
*/
sse.addEventListener("notice", (e) => {
console.log(e.data);
});
/*
* Similarly, this will listen for events
* with the field `event: update`
*/
sse.addEventListener("update", (e) => {
console.log(e.data);
});
/*
* The event "message" is a special case, as it
* will capture events without an event field
* as well as events that have the specific type
* `event: message` It will not trigger on any
* other event type.
*/
sse.addEventListener("message", (e) => {
console.log(e.data);
});
Specifications
| Specification |
|---|
| HTML # the-eventsource-interface |