HTML SSE API

HTML Introduction

HTML Basics

HTML Advanced

HTML Forms

HTML Media

HTML API

HTML SSE API

Server-Sent Events (SSE) enables  a web page to get updates from a server.

1) Server-Sent Events – One Way Messaging

A server-sent event occurs when a web page automatically is update from a server. Before also it was possible, but the web page had to ask if there are any updates available.

2) Receive Server-Sent Event Notifications

The EventSource object receives server-sent event notifications:

Example

				
					<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
  var source = new EventSource("demo_sse.php");
  source.onmessage = function(event) {
    document.getElementById("result").innerHTML += event.data + "<br>";
  };
} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

				
			

Output:

SSE Api

Example explained:

  • Create a new EventSource object, and defines the URL of the page sending the updates (in this example “demo_sse.php”).
  • Each time an update is received, the onmessage event occurs.
  • When an onmessage event takes place, the received data is inserted into the element with id=”result”

Check Server-Sent Events Support

In the tryit example above there were some extra lines of code to check browser support for server-sent events:

if(typeof(EventSource) !== “undefined”) {

  // Yes! Server-sent events support!

  // Some code…..

} else {

  // Sorry! No server-sent events support..

}

Server-Side Code Example

To make the above example work, you require a server that is capable of sending data updates (like PHP or ASP).

The server-side event stream is a simple syntax. Set the “Content-Type” header to “text/event-stream”. Now, the event stream can be sent.

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 explained:

  • Set the “Content-Type” header to “text/event-stream”.
  • Mention the page should not cache.
  • Output the data to send (Always start with “data: “).
  • Flush the output data back must be flushed into the web page.