PostMessage from an isolated iFrame to the main window, the start is always zero

Something fails there about the origin of the event with the postMessage javascript 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…} 

Each document states that it is important to check the event.origin event inside the message event listener. But how to do this if it is always null?

thanks for the help

+12
javascript html5 postmessage
source share
2 answers

Since the iframe is sandboxed, it has lost access to its original data.

adding allow-same-origin to the iframe sandboxed sandbox property will make it work again.

+3
source share

As indicated here , in this scenario there is a great way to determine the sender without granting 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 source is not null , but "null" .

0
source share

All Articles