如何正确使用postMessage与html5和现代浏览器做跨域消息传递?我还是会出错

How to properly use postMessage to do cross-domain messaging with html5 and modern browsers ? I still get errors

本文关键字:消息传递 出错 浏览器 postMessage 何正确 html5      更新时间:2023-09-26

我肯定这里有什么问题,但我不能完全把手指放在它…这里的例子表现得很好,在控制台上没有通知或错误,所以这意味着我的浏览器支持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的文档并等待它说它准备好了(我猜…)。在website.com上,我有一个文件child.html,它是WebsiteA.com的文档中加载的iframe的src,该文件具有以下内容:

<!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结尾)之间工作。它确实有效,但在谷歌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.。html5demos中的例子没有这个错误也可以正常工作。

为什么我得到这个错误,我如何摆脱它

我刚刚试过你的代码,这似乎在Chrome中工作。它使用jsfiddle和jsbin在父窗口和子窗口之间传递消息。

http://jsbin.com/oxesef/4/edit预览

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

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

卡尔