HTML Introduction | HTML5 API | SSE(Server Sent Events)
Server Sent Events API
The Server Sent Events API lets a web page automatically receive updated information from a server.
Major browser versions that support server sent events are as follows.
| API | ie | chrome | firefox | safari | opera |
|---|---|---|---|---|---|
| server sent events | Not supported | 6.0 | 6.0 | 5.0 | 11.5 |
Before using server sent events, first check whether the user’s browser supports them.
Syntax
if (typeof(EventSource) !== "undefined") {
// Code for server sent events
} else {
// Guidance for browsers that do not support server sent events
}
The following example updates a web page every five seconds by using server sent events.
Example
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("/examples/media/sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
}
The server-side PHP file sse.php used in the example above is as follows.
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();
?>
EventSource Object Methods
The example above uses the onmessage event to receive messages.
Other events also exist, and the event methods are as follows.
| Event | Description |
|---|---|
| onopen | When the connection to the server is opened |
| onmessage | When a message is received |
| onerror | When an error occurs |