使用Javascript从父iFrame到子iFrame的跨域通信

使用Javascript从父iFrame到子iFrame的跨域通信,javascript,iframe,cross-domain,parent-child,Javascript,Iframe,Cross Domain,Parent Child,我需要将数据从网页传递到该网页中托管的iFrame。我用window.postMessage。但是,iFrame不接收事件 这是我的代码片段。 父页面: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Test event listener</title> </head> <body>

我需要将数据从网页传递到该网页中托管的iFrame。我用window.postMessage。但是,iFrame不接收事件

这是我的代码片段。 父页面:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>Test event listener</title>
</head>
<body>
<script type="text/javascript">
function SendMsgToIFrame() {
    alert("In Parent window ");
    var myiframe = document.getElementById('myIframe');
    if (myiframe.contentDocument) {
        myiframe.contentDocument.postMessage('Post Message from Parent', '*');
    }
    else if (myiframe.contentWindow) {
        myiframe.contentWindow.postMessage('Post Message from Parent', '*');
    }
</script>
<button type="button" onclick="SendMsgToIFrame()">Push to iframe</button>
<div id="iframeDiv">
<iframe id="myIframe" src="http://localhost:50000/Receiver.htm" width="500" height="200" frameborder=10> 
</iframe>
</div>
</body>
</html>

测试事件侦听器
函数SendMsgToIFrame(){
警报(“在父窗口中”);
var myiframe=document.getElementById('myiframe');
if(myiframe.contentDocument){
myiframe.contentDocument.postMessage('Post Message from Parent','*');
}
else if(myiframe.contentWindow){
myiframe.contentWindow.postMessage('postMessage from Parent','*');
}
推到iframe
Receiver.htm的代码段为:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>Got Text</title>
</head>
<body>
<script type="text/javascript">
    window.attachEvent("onMessage", myhandler);

    function myhandler(mobj) {
        alert("I am in iFrame");
        var message = mobj.data;

        alert("data: " + message);
    }
</script>
<input type="text" name="text1" id="text1" value="text here" /> 
</body>
</html>

收到短信
attachEvent(“onMessage”,myhandler);
函数myhandler(mobj){
警惕(“我在iFrame中”);
var message=mobj.data;
警报(“数据:+消息”);
}
我正在Tomcat(localhost:8080)上运行父页面。iFrame正在我使用httplistener构建的HTTP服务器上运行。 当我运行父页面并点击生成事件的按钮时,我没有收到“我在iFrame中”警报。看起来iFrame根本没有接收到事件。我在这里遗漏了什么?
非常感谢您的帮助。谢谢!

您的代码有一些奇怪的部分。您使用的是
attachEvent
,最好使用
addEventListener
,您可能应该发布到
contentWindow
,而不是文档。

我的代码的问题是: attachEvent(“onMessage”,myhandler)

onmessage应全部为小写。 一旦我把这行改成下面的,它就成功了

window.attachEvent("onmessage", myhandler)

我把答案贴在这里:


该链接还有一个指向github上示例工作代码的链接。

我使用的是IE8。addEventListener不能与IE8一起工作。AttachEvent是IE8的正确方法。我正在发布到内容窗口。我的断点达到了该行。