My goal is to add css to the iframe content from the parent page. I have two different domains one rendering an iframe from the other, I'm using postMessage
to bypass the same-origin
policy issue however this doesn't seem to work as expected. When I try to console.log(iframe.contentWindow)
I get an error in the console Uncaught DOMException: Blocked a frame with origin "http://parent.domain.com" from accessing a cross-origin frame.
iframe
<iframe
sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
src="https://domain.with.iframe.content"
width="100%"
frameBorder="0"
id="iframe-1"
></iframe>
Page with iframe.
<script>
window.addEventListener('message', function(e) {
var iframe = document.getElementById("iframe-1");
console.log(e)
console.log(e.origin)
console.log(iframe)
console.log(iframe.contentWindow)
}, false);
</script>
Page that I'm iframing.
<script>
var body = document.body
body.onload = function resize() {
parent.postMessage(["hey"], "*");
}
</script>
</script>
From the console I can see that the message
event listener is running, however this line console.log(iframe.contentWindow)
throws the error. Any help will be much appreciated, thank you.