0

I have created PostMessage from one domain to another.

in domain A I have frame of domain B. I can send message from A to B. now I want to do opposite of that. I need a button in the frame (on popUp windows). when I click there, I need to send message from B to A.

On domain A:

       <iframe id="frameId" src="http://b.net/2.html" onload="sendCommand();"> </iframe>

            <script  type="text/javascript"> 
                        function sendCommand() {
                        var receiver;
                        receiver = document.getElementById('frameId').contentWindow;
                        receiver.postMessage(receiver, 'http://b.net');
                        }
                </script>
        </body>
    </html>

And in Domain B:

    <!DOCTYPE HTML>
    <html>
    <head>
    <script>
    var F= function(){}
    </script>

    </head>
    <body>
    Hello THere
     <button onclick="F()">Click me</button>
     <script>
            window.addEventListener('message', function(event) {
            alert(event.origin);
    }, false);

    </script>
    </body>

</html>

1 Answers1

0

I solved with this:

is this good solusion?

<!DOCTYPE HTML>
    <html>
    <head>
    <script>
        var t;  
        function load (){       
                 window.addEventListener('message', function(event) {
                        console.log(event.data) ;                   
                        window.clearInterval(t);
                        return;
                }, false);
       }     
    </script>
    </head>
  <body onload="load()">
            <iframe id="frameId" src="http://b.net/2.html"  onload="sendCommand();">  No Frame!</iframe> 
            <script  type="text/javascript"> 
                    function sendCommand() {
                       //  post massage to domain B
                         var receiver = document.getElementById('frameId').contentWindow;
                         receiver.postMessage("Start listening", 'http://b.net');
                    } 
            </script> 
    </body>
</html>


<!DOCTYPE HTML>
<html>
<head>
<script>
var F= function(){  
    // Send message from Iframe Page to domain A
    parent.postMessage("From Iframe Page ","*");
}
</script>
</head>
<body>
Hello There
 <button onclick="F()">Click me</button>
 <script>
        // Listen events
        window.addEventListener('message', function(event) {
        console.log(event.data)
        }, false);

</script>
</body>
</html>