Events
onmessage
Window receives a message sent by another browsing context or itself using postMessage. Window event handler, exposed through the body element in HTML; register on window rather than on an arbitrary element. Event interface: MessageEvent. For the described native event: bubbles: no; cancelable: no. Validate origin and expected source and message shape; specify an exact targetOrigin when possible. Example: Serve over HTTP(S), then click Send local message; opaque-origin previews intentionally do not send. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.
Formal Syntax & Structure
html syntaxhtml
<body onmessage="handleEvent(event)"> window.addEventListener("message", event => { /* handle event */ });Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| onmessage | JavaScript handler body | Optional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute. |
| event | MessageEvent | Event object delivered to the addEventListener callback; event.type is "message". Inspect target, currentTarget, bubbles and cancelable as appropriate. |
Working Example
Example Snippethtml
<p>Window event monitor</p><button id="send" type="button">Send local message</button><p role="status" id="log">Waiting for message</p><script> const target = window; const log = document.getElementById("log"); target.addEventListener("message", event => { log.textContent = String(event.origin === location.origin && event.source === window ? event.data : "Ignored"); }); document.getElementById("send").onclick = () => { if (location.origin !== "null") window.postMessage("hello", location.origin); };</script>