rek*_*kam 12 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>
Run Code Online (Sandbox Code Playgroud)
还有我的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>
Run Code Online (Sandbox Code Playgroud)
查看控制台,即使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…}
Run Code Online (Sandbox Code Playgroud)
在每个文档中,它都说在de"message"事件监听器中检查event.origin很重要.但是如果它总是空的话怎么做呢?
谢谢您的帮助
正如这里所指出的,在这种情况下,有一种非常好的方法来确定发件人,而无需给予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);
Run Code Online (Sandbox Code Playgroud)
请注意,起源不是null,而是"null"。
| 归档时间: |
|
| 查看次数: |
1910 次 |
| 最近记录: |