CKTIS / HTML
onmessage — handling window messages
The onmessage attribute on body sets the Window object's message event handler. It receives messages sent through postMessage, among other uses; check the sender and payload before using received data.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
<body onmessage="handleMessage(event)">
window.onmessage = handleMessage;
window.addEventListener("message", handleMessage);onmessage is an event handler attribute for message. In HTML, it can appear on the body element; it is not a global attribute. Its code handles events on the Window object, not messages addressed to the body element itself. The attribute value is JavaScript code with access to the event parameter.
In JavaScript, window.onmessage = handleMessage sets the same handler. Another assignment replaces it, and assigning null removes it. window.addEventListener("message", handleMessage) registers additional listeners without replacing that handler.
A message sent through postMessage is delivered asynchronously as a MessageEvent: event.data contains the payload, event.origin identifies the sender's origin, and event.source identifies the source. Check the expected origin, source, and payload structure. When sending, specify the exact target origin rather than "*", especially for confidential data. The attribute itself does not send messages.
The example sends a message to the same window. Run it over local HTTP, not as a file: document. The expected result is that Waiting changes to Hello. A CSP that blocks inline code can prevent the script or attribute from executing; in that environment, move the code into an allowed JavaScript file and use addEventListener.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Body onmessage handler</title>
</head>
<body onmessage="if (event.source === window && event.origin === window.origin && event.data === 'Hello') document.getElementById('result').textContent = event.data;">
<p id="result" aria-live="polite">Waiting</p>
<script>
// The destination is this same window, and the payload is not sensitive.
// A wildcard also works when the document has an opaque origin.
window.postMessage('Hello', '*');
</script>
</body>
</html>Result
Hello
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.