-1

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.

oma0256
  • 83
  • 1
  • 8
  • You can't do this, see https://stackoverflow.com/questions/25098021/securityerror-blocked-a-frame-with-origin-from-accessing-a-cross-origin-frame so you'll need to pass the data you need back and forth with postMessage – Milton Apr 29 '20 at 18:06
  • @Milton my goal is to be able to add css to the iframe content from the parent page, how would suggest going about that. Thanks. – oma0256 Apr 29 '20 at 18:11
  • 1
    It depends on how you get the CSS but assuming you have it as a string, you could send that string to the iframe using postMessage. Inside the iframe you could create a style tag, set the innerHTML of that tag to the CSS string and append it to the document head. Like in this article under Global Styles https://dev.to/karataev/set-css-styles-with-javascript-3nl5 – Milton Apr 29 '20 at 18:46
  • 1
    Thanks @Milton it worked, if you could add it as an answer that would be awesome. – oma0256 Apr 29 '20 at 22:05

1 Answers1

2

Adding an answer from my comments:
You can't access iframe.contentWindow from the parent frame, see SecurityError: Blocked a frame with origin from accessing a cross-origin frame
So you'll need to pass the CSS you need back and forth with postMessage.

Depending on how you get the CSS but assuming you have it as a string, you could send that string to the iframe using postMessage. Inside the iframe you could create a style tag, set the innerHTML of that tag to the CSS string and append it to the document head. Like in this article under Global Styles https://dev.to/karataev/set-css-styles-with-javascript-3nl5

Milton
  • 870
  • 4
  • 11