从沙盒iFrame到主窗口的PostMessage,origin始终为null

时间:2016-06-15 14:52:30

标签: javascript html5 postmessage

通过javascript postMessage事件,我无法了解事件来源。

这是我的主页:

<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>

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

我的控制台说:

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&#34; message&#34;事件监听器。但如果它总是空的话怎么办?

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

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

$bucket= "bucket-name"; $filetodownload = "name-of-the-file"; $resultbool = $s3->doesObjectExist ($bucket, $filetodownload ); if ($resultbool) { $result = $client->getObject ( [ 'Bucket' => $bucket, 'Key' => $filetodownload ] ); } else { echo "file not found";die; } header ( "Content-Type: {$result['ContentType']}" ); header ( "Content-Disposition: attachment; filename=" . $filetodownload ); header ('Pragma: public'); echo $result ['Body']; die (); 添加到iframe沙箱属性会使其再次运行。

答案 1 :(得分:0)

here所述,在没有授予allow-same-origin权限的情况下,有一种绝佳的方法来确定发件人:

  // Sandboxed iframes which lack the 'allow-same-origin'
  // header have "null" rather than a valid origin. This means you still
  // have to be careful about accepting data via the messaging API you
  // create. Check that source, and validate those inputs!
  var frame = document.getElementById('sandboxed');
  if (e.origin === "null" && e.source === frame.contentWindow)
    alert('Result: ' + e.data);

请注意,原点不是null,而是"null"