The main difference between the two pages is the method of sending messages. Recieving messages is the same in both.
Send messages to iframe using iframeEl.contentWindow.postMessage
Recieve messages using window.addEventListener('message')
Send messages to parent window using window.parent.postMessage
Recieve messages using window.addEventListener('message')
Thanks for this great live example.
As a security guy, I would add that the message part should be escaped/sanitized (ex: json data should be JSON.parsed) before it's sent to output. also, the origin should be specified by the sender to not disclose any sensitive data to third-party domains and it should be verified by the receiver (event handler) to accept msgs from trusted domains only.