【发布时间】:2014-10-07 21:58:22
【问题描述】:
我们在不同的域中有两个 javascript 文件。对于它们之间的通信,我们使用 postMessage()。 IE 不支持弹出窗口中跨域之间的 postMessage()。 有什么解决办法吗??
【问题讨论】:
我们在不同的域中有两个 javascript 文件。对于它们之间的通信,我们使用 postMessage()。 IE 不支持弹出窗口中跨域之间的 postMessage()。 有什么解决办法吗??
【问题讨论】:
有几个解决方案。
最简单的方法是实际使弹出窗口从与父页面相同的域打开html页面,并且该页面包含一个填充整个弹出窗口的iFrame。然后 iframe 引用另一个域。这样IE就不需要在主页面和popup之间使用postmessage,postmessage发生在popup和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 技巧。
【讨论】: