从沙盒iFrame到主窗口的PostMessage,origin始终为null [英] PostMessage from a sandboxed iFrame to the main window, origin is always null

查看:269
本文介绍了从沙盒iFrame到主窗口的PostMessage,origin始终为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用javascript postMessage事件得不到关于事件来源的事情。

There's something I don't get about the event origin with javascript postMessage event.

这是我的主页:

<html>
<body>

<h1>Test</h1>
<h2>Outside</h2>

<iframe src="iframe-include.html" 
    width="100%" height="100" 
    sandbox="allow-scripts"></iframe>

<script type="text/javascript">
window.addEventListener('message', function (event) {
    console.log(event);
}, false);
</script>

</body>
</html>

我的iFrame内容

<html>
<body>

<h3>Inside</h3>

<script type="text/javascript">
var counter = 1,
    domain = window.location.protocol + '//' + window.location.host,
    send = function () {
        window.setTimeout(function () {
            console.log('iframe says:', domain);
            window.parent.postMessage(counter, domain);
            counter += 1;
            send();
        }, 3000);
    };

send();
</script>

</body>
</html>

查看控制台,即使域变量,事件对象的origin属性也始终为null在iFrame中是正确的。

Looking at the console, the origin property of the event object is always null, even if the domain variable in the iFrame is correct.

我的控制台说:

iframe-include.html:11 iframe says: http://127.0.0.1:8181
iframe.html:11 MessageEvent {isTrusted: true, data: 2, origin: "null", lastEventId: "", source: Window…}

在每个文档中,它都说检查event.origin de de消息事件监听器。但如果它总是为空怎么办呢?

In every doc, it says that it's important to check on event.origin inside de "message" event listener. But how to do that if it's always null?

感谢您的帮助

推荐答案

由于iframe是沙盒,因此无法访问其原始数据。

Since the iframe is sandboxed it lost access to its origin data.

添加 allow-same-origin iframe沙箱属性将使其再次起作用。

adding allow-same-origin to the iframe sandbox property will make it work again.

这篇关于从沙盒iFrame到主窗口的PostMessage,origin始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆