2016-06-15 21 views
8

有些事情我没有通过javascript postMessage事件了解到事件源。从沙盒iFrame到主窗口的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> 

查看控制台,事件对象的origin属性总是空,即使在域变量iFrame是正确的。

我的控制台说:

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是很重要的。但如何做到这一点,如果它总是空?

感谢您的帮助

+0

[无法在'DOMWindow'上执行'postMessage':提供的目标原点与收件人窗口的原点('null')]不匹配(http://stackoverflow.com/questions/22194409/failed- domwindow-the-target-origin-provided-does) –

+0

不,这是一个完全不同的问题,虽然原因是一样的。我也有... – Sych

回答

1

由于iframe被沙箱化,它失去了对原始数据的访问。

allow-same-origin添加到iframe沙箱属性将使其重新工作。