使用 postMessage() 访问 iframe.contentWindow.document 无效

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

我的目标是将 css 添加到父页面的 iframe 内容。我有两个不同的域,一个域从另一个域渲染 iframe,我使用 postMessage 来绕过 same-origin 政策问题,但这似乎没有按预期工作。当我尝试 console.log(iframe.contentWindow) 时,控制台出现错误 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>

带 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>

我正在构建的页面。

<script>
    var body = document.body
    body.onload = function resize() {
        parent.postMessage(["hey"], "*");
    }
</script>
</script>

从控制台我可以看到 message 事件侦听器是 运行,但是这一行 console.log(iframe.contentWindow) 抛出错误。任何帮助将不胜感激,谢谢。

从我的评论中添加一个答案:
您无法从父框架访问 iframe.contentWindow,请参阅 SecurityError: Blocked a frame with origin from accessing a cross-origin frame
所以你需要用 postMessage.

来回传递你需要的 CSS

取决于您获取 CSS 的方式,但假设您将其作为字符串,您可以使用 postMessage 将该字符串发送到 iframe。在 iframe 中,您可以创建一个样式标签,将该标签的 innerHTML 设置为 CSS 字符串并将其附加到文档头部。就像这篇文章中的全局样式 https://dev.to/karataev/set-css-styles-with-javascript-3nl5