4

我确定这里出了点问题,但我不能完全指出它......这里的例子表现得很好,控制台上没有任何通知或错误,所以这意味着我的浏览器支持使用 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 元素,将其附加到 WebsiteA.com 的文档并等待它说它准备好了(我猜......)。在 WebsiteB.com 上,我src在 WebsiteA.com 的文档中加载了 iframe 的 child.html 文件,该文件具有以下内容:

<!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 的控制台中,我得到了经典的. html5demos中的示例工作正常,没有此错误。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.

为什么我会收到此错误以及如何摆脱它?

4

2 回答 2

1

我刚刚尝试了您的代码,这似乎在 Chrome 中有效。它使用 jsfiddle 和 jsbin 在父窗口和子窗口之间传递消息。

http://jsbin.com/oxesef/4/edit#preview

于 2011-10-04T21:10:51.337 回答
0

这不是答案,但可以帮助你。

我使用http://easyxdm.net/wp/来避免这类问题。

卡尔

于 2011-10-04T21:06:51.563 回答