Create a new EventSource object, and specify the URL of the page sending the updates.
When a connection is established, output some text in a <h1> element.
Server-Sent Events are not supported in Internet Explorer.
<!DOCTYPE html> <html> <body> <h1 id="myH1"></h1> <div id="myDIV"></div> <script> if(typeof(EventSource) !== "undefined") { var source = new EventSource("/html/demo_sse.php"); source.onopen = function() {//from w w w. j a v a 2s .com document.getElementById("myH1").innerHTML = "Getting server updates"; }; source.onmessage = function(event) { document.getElementById("myDIV").innerHTML += event.data + "<br>"; }; } else { document.getElementById("myDIV").innerHTML = "Sorry, your browser does not support server-sent events..."; } </script> </body> </html>
The onopen event occurs when a connection with an event source is opened.