gpt4 book ai didi

javascript - 使用 postMessage() 访问 iframe.contentWindow.document 不起作用

转载 作者:行者123 更新时间:2023-12-02 20:54:59 29 4
gpt4 key购买 nike

我的目标是将 css 添加到父页面的 iframe 内容中。我有两个不同的域,其中一个域渲染 iframe,我使用 postMessage 绕过 same-origin 策略问题,但这似乎没有按预期工作。当我尝试 console.log(iframe.contentWindow) 时,我在控制台中收到错误 Uncaught DOMException: Blocked a frame with origin "http://parent.domain.com"from accessing跨源框架。

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>

我正在使用 iframe 的页面。

<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 一样

关于javascript - 使用 postMessage() 访问 iframe.contentWindow.document 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61508437/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com