Arthur Denner
Arthur Denner

Arthur Denner

How to debug postMessages

How to debug postMessages

Log messages between pages and iframes or pop-ups

Arthur Denner's photo
Arthur Denner
Β·Feb 23, 2021Β·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

TL;DR

monitorEvents(window, 'message')
// or
window.addEventListener('message', console.log)

// To stop listening
unmonitorEvents(window, 'message')
// or
window.removeEventListener('message', console.log)

Concept

From the MDN docs:

The window.postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.

That's pretty cool, right?

Demo

Here is a demo of postMessage usage.

Debug

But how can we debug these messages?

Run the following in the Console tab:

// On Safari and Chromium-based browsers
monitorEvents(window, 'message')

// On Firefox
window.addEventListener('message', console.log)
// ^ It works in all the other browsers too

If you're testing in CodeSandbox, run the command in the Console of its detached window.

Cleanup

To stop listening for the messages, run the following:

// On Safari and Chromium-based browsers
unmonitorEvents(window, 'message')

// On Firefox
window.removeEventListener('message', console.log)
// ^ It works in all the other browsers too

Result

After the setup, when receiving messages, you should see something like this:

image.png

That's it!


I hope you enjoyed this post and follow me on any platform for more.

Β 
Share this