EventSource

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.

* Some parts of this feature may have varying levels of support.

La interfaz EventSource se utiliza para recibir eventos server-side. Se realiza la conexión a un servidor sobre HTTP y se reciben eventos en formato text/event-stream sin tener que cerrar la conexión.

Constructor

EventSource()

Crea un nuevo EventSource a partiendo de un valor USVString.

Propiedades

Esta interfaz también heredará propiedades de su antecesor, EventTarget.

EventSource.readyState Read only

Un número representando el estado de la conexión. Los valores posibles son CONECTANDO (0), ABIERTO (1), o CERRADO (2).

EventSource.url Read only

Un valor DOMString representando la URL de la fuente.

EventSource.withCredentials Read only

Un valor Boolean indicando si el objecto EventSource ha sido instanciado con credeciales CORS disponibles (true) o no (false, valor por defecto).

Manejadores de Eventos

EventSource.onerror

En un event handler que se invoca cuando ocurre un error y se envía el evento error a través del objeto EventSource.

EventSource.onmessage

Es un event handler que se invoca cuando se recibe un evento message, que indica que se ha enviado un mensaje desde la fuente.

EventSource.onopen

Es un event handler que se invoca cuando se recibe un evento open, que sucede en el momento que la conexión se abre.

Métodos

Esta interfaz también heredará métodos de su antecesor, EventTarget.

EventSource.close()

Cierra la conexión, si ésta existe, y asigna el valor CLOSED al atributo readyState. Si la conexión ya estaba cerrada, este método no hace nada.

Ejemplos

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

Nota: Está disponible un ejemplo completo en GitHub — ver Simple SSE demo using PHP.

Especificaciones

Specification
HTML
# the-eventsource-interface

Compatibilidad con navegadores

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
EventSource
EventSource() constructor
options.withCredentials parameter
close
error event
message event
open event
readyState
url
withCredentials
Available in workers

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Has more compatibility info.

Ver también