Javascript DOM onmessage Event via onmessage via addEventListener() method

Introduction

Using the addEventListener() method:

Server-Sent Events are not supported in Internet Explorer.

View in separate window

<!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.addEventListener("open", function() {
    document.getElementById("myH1").innerHTML = "Getting server updates";
  });//ww  w. j  a va  2  s  . c o m

  source.addEventListener("message", 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>



PreviousNext

Related