References

Beginner-friendly references for web development, with live, editable examples.

The HTML onmessageerror event

Event All modern browsers Updated
Quick answer

The HTML onmessageerror attribute runs JavaScript when a received message cannot be deserialized. It is an inline handler for the messageerror event; in modern code prefer addEventListener('messageerror', …).

Overview

The onmessageerror event attribute runs JavaScript when a received message fails to deserialize. In JavaScript the event itself is named messageerror. Drop the on prefix when you call addEventListener.

It is a window-level event rather than one tied to a particular element, so it is handled on window. These events cover the page lifecycle, navigation, network status, messaging and similar global concerns.

You can wire this up with the inline onmessageerror HTML attribute, but the modern, recommended approach is window.addEventListener('messageerror', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.

Syntax

<body onmessageerror="handler()"></body>

window.addEventListener('messageerror', handler);

Best practices

  • Prefer window.addEventListener('messageerror', handler) over the inline onmessageerror attribute; it separates behavior from markup and allows multiple handlers.
  • Attach these on window with addEventListener rather than as <body> attributes.
  • Keep these handlers fast; they run at moments that affect the whole page.
  • Remove listeners you no longer need to avoid leaks in long-lived pages.

Frequently asked questions

What is the onmessageerror event?
It runs JavaScript when a received message fails to deserialize. In JavaScript the event is named messageerror.
Where do I attach this event?
On window: these are global events, not tied to a single element.
Can I use it as a body attribute?
Yes. An onmessageerror attribute on <body> is forwarded to the Window object, so the handler is registered on window rather than on the body element itself.
Should I use the onmessageerror attribute or addEventListener?
Prefer window.addEventListener('messageerror', …) in JavaScript. The inline onmessageerror attribute works but mixes behavior into the markup and allows only one handler per element.