繁体   English   中英

如何正确使用postMessage与html5和现代浏览器进行跨域消息传递? 我仍然得到错误

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

我确定这里有问题,但我不能完全指责它...... 这里的例子表现得很好,没有通知或控制台上的错误,所以这意味着我的浏览器支持跨域消息传递与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上,我有一个文件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. 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#preview

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

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

卡尔

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM