简体   繁体   中英

Cross domain communication from parent to child iFrame using Javascript

I need to pass data from a web page to an iFrame hosted in that web page. I used window.postMessage. however the iFrame does not receive the event.

Here is my code snippet. Parent page:

<!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>

Code snippet for Receiver.htm is:

<!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>

I am running the parent page on Tomcat (localhost:8080). The iFrame is running on my HTTP server I built using the httplistener. When I run the parent page and hit the button that generates the event, I do not get the alert "I am in iFrame". Looks like the iFrame is not receiving the event at all. What am I missing here? Any help is very much appreciated. Thanks!

Your code has some strange parts. You're using attachEvent where it's better to use addEventListener and you should probably post to contentWindow , not document.

The problem with my code was this: window.attachEvent("onMessage", myhandler)

onmessage should be all lower case. Once I changed this line to the below, it worked.

window.attachEvent("onmessage", myhandler)

I posted the answer here: javascript cross domain iframe resize

And that link also has a link to sample working code on github.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM