HTML5跨域通信无效

时间:2013-01-25 16:53:04

标签: html5 cross-domain postmessage

我打开1.htm作为 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/ 

这是一个简单的例子。最后,我需要这样的结构: 在域“A”上,我有iframe,它的src是域“B”的页面。在iframe中,有按钮。当我点击iframe中显示的那个按钮时,我需要调用域“A”的window.addEventListener,我该怎么做?

3 个答案:

答案 0 :(得分:2)

如上所述here。你只有以下选择。

相同或不同域方案之间的通信:

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

这纯粹是针对CSRF(跨站点请求伪造)攻击的浏览器限制。看看你的schenario,即使你在同一个领域工作。一种选择是遵循上面的层次结构示例,您可以使用父站点上的帮助页面在页面之间传递消息,甚至在相同或不同的域中传递消息。然后,孩子可以通过这个帮助页面接收和发送消息。

答案 1 :(得分:1)

检查您的主机文件(C:\ Windows \ System32 \ drivers \ etc),确保您没有将localhost映射为其他任何内容。

请注意,通过Javascript访问子框架的父框架不会像这样工作,因为这会带来安全问题(跨站点脚本)。

答案 2 :(得分:1)

解决了这个问题:

<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>
相关问题