最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parent-Iframe postMessage communication - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 8

When 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', '*');
};
发布评论

评论列表(0)

  1. 暂无评论