Javascript DOM onmessage Event

Introduction

Create a new EventSource object, and specify the URL of the page sending the updates.

Each time an update is received, the onmessage event occurs.

When an onmessage event occurs, put the received data into the <div> element with id="myDIV".

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.onopen = function() {/*from www .  j av  a  2s .co m*/
    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 onmessage event occurs when a message is received through an event source.

The event object for the onmessage event supports the following properties:

Property Meaning
data Contains the actual message
origin The URL of the document that invoked the event
lastEventId the identifier of the last message seen in the event stream



PreviousNext

Related