2

I open 1.htm as a http://127.0.0.1/1.html

1.html

<!DOCTYPE html>
<html>
<head>

    </head>
    <body>
       <iframe   id="ifr" src="http://localhost/2.html" width="100%" height="300">
       </iframe>       
        <script>  
            iframe=document.getElementById("ifr");
            iframe.contentWindow.postMessage("hello there", "http://localhost");
     </script>  
    </body> 
    </html>

2.html

<!DOCTYPE html>
<html>
<head>
 <script>
    window.addEventListener("message", function(event) {

    alert(hi);
        if (event.data === "hello there" ) {
            alert("Hi" + event.origin);
        }
    }, false );
</script>

<head>
<body>
Hello world
</body>

"

but I have that error: "Unable to post message to   http://localhost. Recipient has origin  http://127.0.0.1/ 

that's simple example. finally, I need structure like that: On domain "A", I have iframe and it's src is page of domain "B". in iframe, there is button. when i click to that button, which is shown inside iframe, I need to call window.addEventListener of domain "A" how can i do that?

3 Answers3

2

As described here. you only have following options.

Communication between same or different domain scenarios:

 +-------------------------+-----------+-------------+-------------+
 |                         | home.html | framed.html | helper.html |
 +-------------------------+-----------+-------------+-------------+
 | www.foo.com/home.html   |    N/A    |     YES     |     YES     |
 | www.bar.net/framed.html |    NO     |     N/A     |     YES     |
 | www.foo.com/helper.html |    YES    |     YES     |     N/A     |
 +-------------------------+-----------+-------------+-------------+

This is purely browser restriction for CSRF (Cross Site Request Forgery) attack. Looking at your schenario, even you are working in same domain. One option is to follow above example of hierarchy, where you can pass messages between pages, even within same or different domains using a helper page on parent site. Then child can take and send messages through this helper page.

Community
  • 1
  • 1
Nexus23
  • 5,607
  • 8
  • 43
  • 64
1

Check your host file (C:\Windows\System32\drivers\etc) ensure you dont have localhost mapped as anything else.

Note accessing the parent frame from the child via Javascript doesnt work like this as this poses a security issue( Cross Site Scripting ).

Waqar
  • 758
  • 4
  • 15
1

solved by that:

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

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