I'm trying to set up a simple postmessage munication 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.
I'm trying to set up a simple postmessage munication 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.
Share Improve this question edited Jul 25, 2017 at 7:48 Muddu Patil 7211 gold badge11 silver badges24 bronze badges asked Nov 22, 2013 at 11:12 user2958009user2958009 311 silver badge4 bronze badges 1- Set name to iframe and send message to iframe using window.frames[<index/name>] – Murali Mopuru Commented Nov 23, 2013 at 16:42
1 Answer
Reset to default 8When you send message to iframe, it is not loaded yet. Use "onload" event to start munication with iframe.
ifr.onload = function() {
this.contentWindow.postMessage('hello child, this is parent', '*');
};