首页 > 解决方案 > 使用 srcdoc 时的 iframe 跨域问题

问题描述

我需要显示来自用户的 html 输入,我不希望用户能够在这里使用脚本,所以我使用 iframe 的沙盒模式来获得没有脚本的内容。

<iframe class="frame"
        srcdoc="<h1>title</h1><p>content1</p><p>content2</p>"
        sandbox=""
        style="width:100%;border:none;overflow:hidden;">
 </iframe>

问题是我希望能够调整此框架的大小以使其内容的高度与波纹管功能相匹配,但iFrame.contentWindow.document由于跨域,我无法访问。

function resizeIFrameToFitContent( iFrame ) {
    iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
    iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}

有没有办法解决这个问题?

标签: javascripthtmliframecross-domain

解决方案


最后我解决了这个问题。问题来自限制一切的沙盒模式,因此我需要允许来自同一来源的 javascript 能够从我的页面访问它:

<iframe class="frame"
        srcdoc="<h1>title</h1><p>content1</p><p>content2</p>"
        sandbox="allow-same-origin"
        style="width:100%;border:none;overflow:hidden;">
 </iframe>

推荐阅读