我确信这里出了问题,但我不能完全指出它......这个例子here表现良好,控制台上没有任何通知或错误,因此这意味着我的浏览器支持使用 html5 进行跨域消息传递(当然是这样,它是 Chrome 14..)。
我的代码或多或少执行以下操作:WebsiteA.com 中加载的脚本创建了一个 iframe 并将其附加到 WebsiteA.com 的文档中。附加的框架将包含 WebsiteB.com,加载时,它必须向其父级 WebsiteA.com 发送一条消息,告诉它 WebsiteB.com 已准备好接收一些 JSON。当 WebsiteA.com 收到此消息时,它会发回 JSON。
所以 WebsiteA.com 之前有一行</body>
像这样:<script scr="http://WebsiteB.com/load-my-iframe.js" type="text/javascript"></script>
,并且在里面load-my-iframe.js
,我有以下内容:
var child = document.createElement('iframe');
child.src = 'http://WebsiteB.com/child.html';
var body = document.getElementsByTagName('body')[0]
body.appendChild(child);
var SomeJSON = {"something" : "that WebsiteB should have"};
window.onmessage = function (e) {
if (e.origin === 'http://WebsiteB.com' && e.data === 'ready') {
e.source.postMessage(SomeJSON, 'http://WebsiteB.com');
}
}
这样就创建了 iframe 元素,将其附加到 WebsiteS.com 文档并等待它说它已准备好(我猜......)。在 Website.can 上,我有文件 child.html ,它是src
Website.com 文档中加载的 iframe 的文件,该文件具有以下内容:
<!DOCTYPE html>
<html lang="pt">
<head>
<title>WebsiteB.com</title>
<script type="text/javascript">
window.onload = function () {
window.parent.postMessage('ready','*');
}
window.addEventListener('message', receiveMessage, false);
function receiveMessage(event) {
if (event.data.something === "that WebsiteB should have") {
document.write('It worked!');
}
}
</script>
</head>
<body>
</body>
</html>
现在奇怪的事情是:
遗憾的是,我不拥有 WebsiteA.com 和 WebsiteB.com,但我设法在一个顶级域和一个子域(以 .no.de 结尾)之间工作。它确实有效,但在 Google Chrome 14 的控制台中我得到了经典Unsafe JavaScript attempt to access frame with URL http://WebsiteA.com/ from frame with URL http://WebsiteB.com/child.html. Domains, protocols and ports must match.
. The html5demos 中的示例没有这个错误就可以正常工作。
为什么会出现此错误以及如何消除它?