HTML Server-Sent Events
- Previous Page HTML5 Web Workers
- Next Page HTML Examples
Server-Sent events allow web pages to obtain updates from the server.
Server-Sent Event - One Way Messaging
Server-Sent events refer to web pages automatically obtaining updates from the server.
This could also be done in the past, provided 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, etc.
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>"; };
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..... } // Sorry! Server-sent events are not supported! }
Server-side code example
In order for the example to 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.
PHP Code (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(); ?>
ASP Code (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 output data to the web page
EventSource Object
In the example above, we use the onmessage event to receive messages. However, other events can also be used:
Event | Description |
---|---|
onopen | When the connection to the server is opened |
onmessage | When a message is received |
onerror | When an error occurs |
- Previous Page HTML5 Web Workers
- Next Page HTML Examples