问题
There's something I don't get about the event origin with javascript postMessage event.
Here is my main page:
<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>
And my iFrame content
<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>
Looking at the console, the origin property of the event object is always null, even if the domain variable in the iFrame is correct.
My console says:
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…}
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?
Thanks for the help
回答1:
Since the iframe is sandboxed it lost access to its origin data.
adding allow-same-origin
to the iframe sandbox property will make it work again.
回答2:
As pointed out here, there is a perfectly fine way to determine the sender in that scenario, without giving the allow-same-origin
permission:
// 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);
Note that the origin isn't null
, it's "null"
.
来源:https://stackoverflow.com/questions/37838875/postmessage-from-a-sandboxed-iframe-to-the-main-window-origin-is-always-null