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 triggers the event
- lastEventId - Identifier of the last message seen in the event stream
Related Events:
For more information on Server-Sent Events (Server-Sent Events), please learn from 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 every 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>"; };
Example 2
Get the URL of the document that triggers 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/
Syntax
object.onmessage = function(){myScript};
Using addEventListener() Method:
object.addEventListener("message", myScript);
Note:Internet Explorer 8 or earlier versions do not support addEventListener() Method.
Technical Details
Bubble: | Not Supported |
---|---|
Cancellable: | Not Supported |
Event Type: | Event |
Browser Support
The numbers in the table indicate the first browser version that fully supports the event.
Events | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
onmessage | 9.0 | Not Supported | 6.0 | 5.0 | 11.0 |