【问题标题】:HTML5 cross-domain communication is not workingHTML5 跨域通信不起作用
【发布时间】:2013-01-09 16:42:52
【问题描述】:

我以 http://127.0.0.1/1.html

的形式打开 1.htm

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 我该怎么做?

【问题讨论】:

    标签: html cross-domain postmessage


    【解决方案1】:

    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(跨站请求伪造)攻击的浏览器限制。查看您的方案,即使您在同一个域中工作。一种选择是遵循上面的层次结构示例,您可以在页面之间传递消息,甚至在相同或不同域中使用父站点上的帮助页面。然后孩子可以通过这个帮助页面接收和发送消息。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        解决了:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-12-05
          • 2011-12-27
          • 1970-01-01
          • 2013-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-14
          相关资源
          最近更新 更多