Issue communication with postMessage from parent t

2019-07-07 05:35发布

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 ?

2条回答
孤傲高冷的网名
2楼-- · 2019-07-07 06:02

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

查看更多
三岁会撩人
3楼-- · 2019-07-07 06:19

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 $()

查看更多
登录 后发表回答