HTML Server-Sent Events

Server-Sent events allow web pages to obtain updates from the server.

Server-Sent Events - One Way Messaging

Server-Sent events refer to web pages automatically obtaining updates from the server.

This could also be done before, on the condition that the web page had to ask if there were any available updates. With Server-Sent events, updates can arrive automatically.

For example: Facebook/Twitter updates, stock price updates, new posts, sports results, and so on.

Browser Support

The numbers in the table indicate the first browser that fully supports server-sent events.

API
SSE 6.0 Not supported 6.0 5.0 11.5

Receive Server-Sent Event Notifications

The EventSource object is used to receive server-sent event notifications:

Example

var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
    document.getElementById("result").innerHTML += event.data + "<br>";
};

Try It Yourself

Example Explanation:

  • Create a new EventSource object and specify the URL of the page that sends updates (in this example, "demo_sse.php")
  • An onmessage event occurs every time an update is received
  • When the onmessage event occurs, push the received data into the element with id "result"

Detect Server-Sent Event Support

In the TIY instance, we wrote some additional code to detect browser support for server-sent events:

if(typeof(EventSource) !== "undefined") {
    // Yes! Server-sent events are supported!
    // Some code.....
} else {
    // Sorry! Server-sent events are not supported!
}

Server-side code example

To make the example run, you need to be able to send data update servers (such as PHP or ASP).

The syntax of server-side event streams is very simple. Set the header "Content-Type" to "text/event-stream". Now, you can start sending event streams.

Code in PHP (demo_sse.php):

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

Code in ASP (VB) (demo_sse.asp):

<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: The server time is: " & now())
Response.Flush()
%>

Code Explanation:

  • Set the header "Content-Type" to "text/event-stream"
  • Specify that the page should not be cached
  • Output the date to be sent (always starts with "data: ")
  • Refresh the web page with output data

EventSource Object

In the example above, we use the onmessage event to get the message. However, other events can also be used:

Event Description
onopen When a connection to the server is opened
onmessage When a message is received
onerror When an error occurs