HTML5 Server-Sent Events

HTML5 server-sent event allows web pages to get updates from the server.

Server-Sent event-one-way messaging

The Server-Sent Event (SSE) refers to the web page automatically getting updates from the server.

It was possible to do this in the past, provided that the web page had to ask if an update was available. By sending events through the server, updates can arrive automatically.

Examples: Facebook/Twitter updates, stock price updates, new blog posts, event results, etc.

Browser support

Internet Explorer Firefox Opera Google Chrome Safari

All major browsers support the server to send events, except Internet Explorer.

Receive Server-Sent event notification

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


var source=new EventSource("demo_sse.php");
    document.getElementById("result") + "<br>";

Example analysis:

  • Create a new EventSource object, and then specify the URL of the page where the update will be sent ("demo_sse.php" in this example)

  • Every time an update is received, an onmessage event occurs

  • When the onmessage event occurs, push the received data into the element with id "result"

Detect Server-Sent event support

In the following example, we have written an additional piece of code to detect the browser support of the server sending events:

     // Browser supports Server-Sent
     // Some code.....
     // The browser does not support Server-Sent...

Server-side code example

In order for the above example to work, you also need a server (such as PHP and ASP) that can send data updates.

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


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

ASP code (VB) (demo_sse.asp):

Response.Write("data: " & now())

Code explanation:

  • Set the header "Content-Type" to "text/event-stream"

  • Specifies not to cache the page

  • Output sending date (always start with "data: ")

  • Refresh the output data to the web page

EventSource object

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

onopenWhen the connection to the server is opened
onmessageWhen a message is received
onerrorWhen an error occurs