HTML: Server-Sent Events (SSE) API with Examples

How to use SSE API - Server-Sent Events

HTML: Server-Sent Events (SSE)

{tocify} $title={Table of Contents}

Server-Sent Events (SSE) permit a web page to obtain updates from a server.

Server-Sent Events - One Way Messaging

A server-sent event is when a web page automatically obtains updates from a server.

This was even possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates arrive automatically.

Examples: Facebook/Twitter updates, stock price updates, news feeds, sports results, etc.

Receive Server-Sent Event Notifications

The EventSource object is utilised to obtain server-sent event notifications:

Example

<!DOCTYPE html>
<html>
<body>

<h3>Getting server updates</h3>

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

</body>
</html>{codeBox}

Example explained:

  • Make a new EventSource object, and identify the URL of the page sending the updates (in this example, "demo_sse.php")
  • Each time an update is obtained, the onmessage event occurs
  • When an onmessage event occurs, put the obtained data into the element with id="result"

Check Server-Sent Events Support

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

if(typeof(EventSource) !== "undefined") {
  // Yes! Server-sent events support!
  // Some code.....
} else {
  // Sorry! No server-sent events support..
}{codeBox}

Server-Side Code Example

For the example above to work, you require a server capable of sending data updates (like PHP or ASP).

The server-side event stream syntax is straightforward. Set the "Content-Type" header 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();
?>{codeBox}

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()
%>{codeBox}

Code explained:

  • Specify the "Content-Type" header to "text/event-stream"
  • Determine that the page should not cache
  • Output the data to send ( always start with "data: " )
  • Flush the output data back to the web page

The EventSource Object

In the examples above, we utilised the onmessage event to obtain messages. But other events are also available:

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

Conclusion:

Friends, according to my expertise, I have written complete information to help you with “HTML SSE API.” If this post is favourable for you or not, please tell me by commenting.

If you liked this post, do not forget to share it with your friends so they can get information about it.

You can ask us through comments if you still have questions or doubts, I will answer all your questions, and you can contact us for more information.

Please tell us through the comment section if you think we miss anything.

To be published, comments must be reviewed by the administrator.*

Previous Post Next Post