Search code examples
javascriptsame-origin-policypostmessage

Accessing iframe.contentWindow.document not working using postMessage()


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.


Solution

  • 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