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
postMessage in your web app sends to the main document's window , not to the iframe's. Specify the iframe's window object: document. getElementById('cross_domain_page').
The sandbox attribute enables an extra set of restrictions for the content in the iframe. When the sandbox attribute is present, and it will: treat the content as being from a unique origin. block form submission. block script execution.
postMessage() The window. postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.
Applying the sandbox attribute to iframes you include allows you to grant certain privileges to the content they display, only those privileges which are necessary for the content to function correctly.
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With