Parent-Iframe postMessage communication

iframe, javascript

Solution

When you send message to iframe, it is not loaded yet. Use "onload" event to start communication with iframe.

ifr.onload = function() { 
    this.contentWindow.postMessage('hello child, this is parent', '*');
};

Problem

I'm trying to set up a simple postmessage communication between a parent window and an iframe contained inside it. I got this code on the parent side: ``` var ifr = document.getElementById("ifr"); ifr.contentWindow.postMessage('hello child, this is parent', '*'); window.addEventListener('message', function (e) { console.log(e.data) }); ``` And on the child side I have: ``` window.parent.postMessage('hello parent, this is child', '*') window.addEventListener('message', function (e) {console.log(e.data) } ); ``` I receive the message sent by the iframe but not the one sent by the parent, I've checked and the iframe element is being correctly selected by the get. This is just for testing purposes to use on something else.

Original source