EventSource

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 EventSource.close() .

Once the connection is opened, incoming messages from the server are delivered to your code in the form of events. If there is an event field in the incoming message, the triggered event is the same as the event field value. If no event field is present, then a generic message event is fired.

不像 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 .

When not used over HTTP/2 , SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). The issue has been marked as "Won't fix" in Chrome and Firefox . This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com. (from Stackoverflow ). When using HTTP/2, the maximum number of simultaneous HTTP streams is negotiated between the server and the client (defaults to 100).

构造函数

EventSource()
创建新的 EventSource to handle receiving server-sent events from a specified URL, optionally in credentials mode.

特性

This interface also inherits properties from its parent, EventTarget .

EventSource.readyState 只读
A number representing the state of the connection. Possible values are CONNECTING ( 0 ), OPEN ( 1 ),或 CLOSED ( 2 ).
EventSource.url 只读
A DOMString representing the URL of the source.
EventSource.withCredentials 只读
A Boolean indicating whether the EventSource object was instantiated with cross-origin ( CORS ) credentials set ( true ), or not ( false ,默认)。

事件处理程序

EventSource.onerror
Is an EventHandler called when an error occurs and the error event is dispatched on an EventSource 对象。
EventSource.onmessage
Is an EventHandler called when a message event is received, that is when a message is coming from the source.
EventSource.onopen
Is an EventHandler called when an open event is received, that is when the connection was just opened.

方法

This interface also inherits methods from its parent, EventTarget .

EventSource.close()
Closes the connection, if any, and sets the readyState attribute to CLOSED . 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.

范例

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.

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 <li> element and writes the message's data into it, then appends the new element to the list element already in the document.

注意 : You can find a full example on GitHub — see Simple SSE demo using PHP.

To listen to named events, you'll require a listener for each type of event sent.

  const sse = new EventSource('/api/v1/sse');
  /* This will listen only for events
   * similar to the following:
   *
   * event: notice
   * data: useful data
   * id: someid
   *
   */
  sse.addEventListener("notice", function(e) {
    console.log(e.data)
  })
  /* Similarly, this will listen for events
   * with the field `event: update`
   */
  sse.addEventListener("update", function(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", function(e) {
    console.log(e.data)
  })
					

规范

规范 状态
HTML Living Standard
The definition of 'EventSource' in that specification.
实时标准

    浏览器兼容性

    更新 GitHub 上的兼容性数据
    Desktop Mobile
    Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
    EventSource Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera 11 Safari 5 WebView Android ≤37 Chrome Android 18 Firefox Android 45 Opera Android 11 Safari iOS 5 Samsung Internet Android 1.0
    EventSource() 构造函数 Chrome 9 Edge 79 Firefox 6 IE 不支持 No Opera 11 Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    close Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera Yes Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    error event Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera Yes Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    message event Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera Yes Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    onerror Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera Yes Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    onmessage Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera Yes Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    onopen Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera Yes Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    open event Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera Yes Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    readyState Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera Yes Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    url Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera Yes Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    withCredentials Chrome 6 Edge 79 Firefox 6 IE 不支持 No Opera Yes Safari 5 WebView Android Yes Chrome Android 18 Firefox Android 45 Opera Android 12 Safari iOS 5 Samsung Internet Android 1.0
    Available in workers Chrome Yes Edge 79 Firefox 53 IE 不支持 No Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 53 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes

    图例

    完整支持
    完整支持
    不支持
    不支持

    另请参阅