在IE10中不能使用的跨域窗口之间的postMessage(适用于帧)

Kin*_*wen 6 internet-explorer postmessage cross-domain addeventlistener

我按照本教程http://davidwalsh.name/window-postmessage,创建了跨域消息传递脚本,可以在Chrome和Firefox中使用,但不能在IE 10中使用.有人能给我一些关于如何修改IE 8+的点击吗?

在一个服务器(例如:192.168.15.223) - 接收器

<script>
//listener
window.addEventListener('message',function(event) {
    if(event.origin !== 'http://120.0.0.211') return;
    document.getElementById('cc').innerHTML = event.data;
},false);

window.attachEvent('onmessage',function(event) {
    if(event.origin !== 'http://120.0.0.211') return;
    document.getElementById('cc').innerHTML = event.data;
},false);
</script>
<p>At 192.18.15.223 server</p>
<div id='cc'>Nothing received yet</div>
Run Code Online (Sandbox Code Playgroud)

在另一台服务器(例如:120.0.0.211) - 发件人

<script>
//create popup window
var domain = 'http://192.18.15.223';
var myPopup = window.open(domain + '/receiver','myWindow','width=400,height=200');
//message sender
function popup(){
    var message = 'A message sent from 120.0.0.211:';
    myPopup.postMessage(message,domain); //send the message and target URI 
}
</script>
<div id="bb">At 120.0.0.211 server</div>
<button type="button" onclick="popup()">send the message!</button>
Run Code Online (Sandbox Code Playgroud)

上面的脚本在Chrome和Firefox中完美运行,窗口弹出并且可以接收消息,但是在IE(8+)中它只弹出窗口但是没有接收到消息(或者可能无法发送).

我的主要目的是让两个域发送和接收简单数据(文本,单张照片等),并且不在后端包含太多变化.所以不考虑web服务.

任何帮助将不胜感激!

以下是一些可能有助于调查问题的链接.

  1. 这篇文章使用了IE上的attachEvent,我已经在上面的代码中做了: Internet Explorer中的addEventListener

  2. 这个微软官方文档显示IE 8+应该支持addEventListener:http://msdn.microsoft.com/en-us/library/ie/cc197057( v = vs.85) .aspx

  3. 这推荐使用Jquery bind()来替换addEventListener: jQuery相当于JavaScript的addEventListener方法

Kin*_*wen 4

IE不支持跨域弹出窗口之间的postMessage(例如:window.open)。IE 确实支持嵌入框架的 postMessage(例如:top.frames)。

所以我最终将一个框架放入对话框中,假装像一个弹出窗口。例如:

借助 Jquery UI 对话框

<script>
$("#dialog").dialog({
    autoOpen: false,
    modal: true,
    height: 300,
weight: 400,
});

function openiframe(){
   $('#dialog').dialog('open');
});
</script>

<p>At 120.0.0.211 server</p>
<button type="button" onclick="openiframe()">send the message!</button>
<div id="dialog">
   <iframe id="iframe" src="http://192.168.15.223/smallframe"></iframe>
</div>
Run Code Online (Sandbox Code Playgroud)

可能还有其他解决方案/技术用于跨域窗口之间的交换:

  1. 使用 Ajax 的跨域资源共享 (CORS)

  2. 使用像 REST 这样的 Web 服务,这实际上是服务器到服务器的交换,不再是服务器-浏览器-服务器结构。但这是我们向另一台服务器发送消息的一种方式。对于某些框架,很容易设置 REST,例如:cakephp