【问题标题】:Iframe cross-origin issue when using srcdoc使用 srcdoc 时的 iframe 跨域问题
【发布时间】:2021-09-08 04:14:09
【问题描述】:

我需要显示来自用户的输入,即 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;
}

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

【问题讨论】:

    标签: javascript html iframe cross-domain


    【解决方案1】:

    最后我解决了这个问题。问题来自限制一切的沙盒模式,因此我需要允许来自同一来源的 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>
    

    【讨论】:

      猜你喜欢
      • 2012-03-12
      • 2012-12-11
      • 2011-02-18
      相关资源
      最近更新 更多