Issue communication with postMessage from parent to child iFrame

a 夏天 提交于 2019-12-23 17:59:10

问题


I'm having an issue communicating from my parent window to the child iFrame. But in the other side, everything works perfectly. Here is how I get the chil iFrame object in order to fire the postMessage function:

var iFrame = document.getElementById('Frame').contentWindow;

When I print it int he console, I get the following:

Window {parent: Window, opener: null, top: Window, length: 0, frames: Window…}

When I proceed to the postMessage function as follows:

iFrame.postMessage("message", "http://contoso.com");

It shows me an error when loading the page: iFrame.postMessage is not a function. When I execute the postMessage in console, I get an undefined

What am I doing wrong ?


回答1:


try this

var iFrame = document.getElementById('Frame');
iFrame.contentWindow.postMessage("message", "http://contoso.com");

I had this problem too. I found solution from this website https://www.viget.com/articles/using-javascript-postmessage-to-talk-to-iframes




回答2:


Below code also works.

$('#id')[0].contentWindow.postMessage("hello world",targetOrigin);

There is a difference between jQuery selector and document.getElementById.

Document.getElementByID returns HTML DOM object.
jQuery selector returns jQuery object.

For more information please find below link. document.getElementById vs jQuery $()



来源:https://stackoverflow.com/questions/40991114/issue-communication-with-postmessage-from-parent-to-child-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!