Link to home
Start Free TrialLog in
Avatar of Stacey Fontenot
Stacey Fontenot

asked on

Post a message from child to parent

I have an iframe in a web page that needs to listen for a message from a child page within an iframe. I'm having an issue making this happen. Anyone have a clue why?

Parent...
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        // Create IE + others compatible event handler
        var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
        var eventer = window[eventMethod];
        var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

        // Listen to message from child window
        eventer(messageEvent, function (e) {
            console.log('parent received message!:  ', e.data);
        }, false);
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <iframe src="child.aspx"></iframe>
    </div>
    </form>
</body>
</html>

Child...
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        // Every two seconds....
        function sendMessage() {
            // Send the message "Hello" to the parent window
            // ...if the domain is still "davidwalsh.name"
            parent.postMessage("Hello", "http://localhost:49646/Child.aspx");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Hello world. This is the child.
    </div>
    </form>
</body>
</html>
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial