Content · Web Development · HTML

HTML message DOM Event: Reference and Examples

Learn when the message DOM event fires and how to handle it with JavaScript using a practical HTML example.

1 views Published Oct 19, 2026 Updated Oct 19, 2026 Admin

When someone interacts with a webpage, the browser sends events to the relevant JavaScript code. The message event happens when a message arrives from a permitted messaging API.

When message happens


A message arrives from a permitted messaging API.

You can listen for it using addEventListener(). That keeps event handling separate from HTML attributes such as onclick and works well with modern code organization.

A small working example


<button id="send-message" type="button">Send a test message</button>
<p id="event-status" role="status">Waiting for message...</p>
<script>
    const eventStatus = document.getElementById("event-status");
    window.addEventListener("message", (eventDetails) => {
        if (eventDetails.origin !== window.location.origin) return;
        eventStatus.textContent = String(eventDetails.data);
    });
    document.getElementById("send-message").addEventListener("click", () => {
        window.postMessage("A safe local message", window.location.origin);
    });
</script>

Reading the code


The browser listens for message on the relevant target. When the event occurs, the callback receives eventDetails, updates the status message and logs the event name and target in Developer Tools.

Send postMessage from another browsing context and always check origin.

Check eventDetails.origin and the message schema before trusting eventDetails.data.

Some events need a specific browser condition, another tab or window, or a Web Component to reproduce. Read the trigger steps carefully before deciding that an event handler is not working.

Try it in your browser


Open the page, show the Console panel, and follow this test: Send postMessage from another browsing context and always check origin. Then change one thing in the example and observe whether the event still fires.

Common Beginner Mistakes


  • Expecting message to fire without its required user action or browser condition.
  • Send postMessage from another browsing context and always check origin.
  • Adding repeated event listeners without considering cleanup or unwanted side effects.

Key Takeaways


  • message reports a message arrives from a permitted messaging API.
  • addEventListener("message", ...) listens for the event on the appropriate target.
  • Send postMessage from another browsing context and always check origin.
Share this resourceSend this page to someone who may find it useful.