跨域弹出窗口之间的postMessage

时间:2014-08-14 09:38:28

标签: cross-domain postmessage

我们在不同的域中有两个javascript文件。对于它们之间的通信,我们使用postMessage()。 IE不支持弹出窗口中跨域之间的postMessage()。 任何解决方案?

1 个答案:

答案 0 :(得分:1)

有很多解决方案。

最简单的方法是实际制作弹出窗口从与父页面相同的域打开html页面,此页面包含一个填充整个弹出窗口的iFrame。 iframe然后引用另一个域。这样IE不需要在主页面和弹出窗口之间使用postmessage,postmessage发生在popup和iframe之间,所有浏览器都支持iframe。

它可以看起来像这样:

主页

 <html>
     <head>
     <script>
        var popup = null;

        $(document).ready(function() {
            popup = window.open("Popup.html");
        }

        function DoStuff() {
            popup.SendMessage("Hello World");
         }
     </script>
     </head>
     <body>
         <button onclick="javascript:DoStuff()">Test</button>
     </body>
 </html>

Popup.html(与主页位于同一个域中)

 <html>
     <head>
     <script>
         function SendMessage(message) {
             $("#targetIframe").contentWindow.postMessage(message, '*');
         }
     </script>
     </head>
     <body>
         <!-- TODO: fill whole window with css -->
         <iframe id="targetIframe" src="http://otherdomain/Target.html"/>
     </body>
 </html>

Target.html应该接收正常的邮寄消息。

此解决方案适用于任何浏览器。 还有一个名为porthole(http://ternarylabs.github.io/porthole/)的现成跨域通信库,如果浏览器支持它,它使用postmessage。我已经使用过了,效果很好。问题是设置有点复杂,因此我建议使用这个弹出式iframe技巧。

相关问题