onmessage event

Definition and usage

An onmessage event occurs when a message is received through an event source.

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

  • data - Contains the actual message
  • origin - URL of the document that calls the event
  • lastEventId - Identifier of the last message seen in the event stream

Related events :

  • onopen - Occurs when the connection with the server is opened
  • onerror - Occurs when an error occurs

For more information on Server-Sent Events (Server-Sent Events), please learn our HTML5 Server-Sent Events Tutorial.

Instance

Example 1

Create a new EventSource object and specify the URL of the page that sends updates.

An onmessage event occurs each time an update is received. When an onmessage event occurs, the received data is placed in the <div> element with id="myDIV" :

var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
  document.getElementById("myDIV").innerHTML += event.data + "<br>";
};

Try it yourself

Example 2

Get the URL of the document that calls the onmessage event :

var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
  document.getElementById("myDIV").innerHTML = event.origin;
};

The result will be :

https://www.codew3c.com/

Try it yourself

Syntax

object.onmessage = function(){myScript};

Try it yourself

Use addEventListener() method :

object.addEventListener("message", myScript);

Try it yourself

Note :Internet Explorer 8 or earlier versions do not support addEventListener() method.

Technical details

Bubble : Non pris en charge
Cancellable : Non pris en charge
Type d'événement : Event

Support du navigateur

Les numéros dans le tableau indiquent la version du navigateur qui prend en charge complètement cet événement.

Événements Chrome IE Firefox Safari Opera
onmessage 9.0 Non pris en charge 6.0 5.0 11.0