onmessage

The onmessage event is triggered when a message is received via an event source. The event object for this event includes the following properties.

onmessage event

The onmessage event activates a <script> when a message is received from another window or iframe. It is often used with the postMessage API to enable cross-origin communication.

Syntax

In HTML

index.html
<element onmessage="myScript">

In JS

script.js
object.onmessage = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("message", myScript);

Example

::event-onmessage ::
<h1 id="myH1"></h1>
<div id="myDIV"></div>
<p><strong>Note:</strong> Server-Sent Events are not supported in Internet Explorer.</p>

Values

Conclusion

The onmessage event is essential for handling messages sent between different windows or iframes. It is frequently used with the postMessage API for secure cross-origin communication. This event enables real-time data exchange between different parts of a web application.