HTML Server-Sent Events API
The Server-Sent Events (SSE) API lets a server push messages and updates to a web page over an HTTP connection.
Server-Sent Events - One Way Messaging
A server-sent event is when a web page automatically receives messages or updates from a server. Normally a page has to request data from the server, but with server-sent events the updates are pushed automatically. Examples include social media updates, stock market updates, news feeds, and sports results.
Browser Support
The Server-Sent Events API is supported in all modern browsers (from Chrome 6, Edge 79, Firefox 6, Safari 5, and Opera 11.5).
Receive Server-Sent Event Notifications
The EventSource object receives server-sent event notifications. You create a new EventSource and give it the URL of the page sending the updates. Each time an update arrives, the onmessage event fires, and you put the received data into an element on the page.
Example
Receiving server-sent events with EventSource.
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sse Receive</title>
</head>
<body>
<p id="result"></p>
<script>
const x = document.getElementById("result");
// Check browser support for SSE
if (typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
x.innerHTML += event.data + "<br>";
};
} else {
x.innerHTML = "Sorry, no support for server-sent events.";
}
</script>
</body>
</html>
Check Browser Support
The example above includes a few extra lines to check browser support, by testing typeof(EventSource) and running the SSE code only if it is defined, otherwise showing a no-support message.
Server-Side Code Example
For the example to work, you need a server that can send data updates (such as PHP or ASP). The server-side event stream syntax is simple: set the Content-Type header to text/event-stream, say the page should not cache, output the data (always starting each message with data:), and flush it back to the page. In PHP this means setting the header with header('Content-Type: text/event-stream'), echoing a line like data: The server time is: ..., and calling flush(); in ASP you set Response.ContentType = "text/event-stream", write the data: line, and call Response.Flush().
The EventSource Object
The examples use the onmessage event, but other events are available too: onopen fires when a connection to the server is opened, onmessage fires when a message is received, and onerror fires when an error occurs.