【问题标题】:How to get the height of a sandboxed iframe?如何获得沙盒 iframe 的高度?
【发布时间】:2018-03-20 15:20:34
【问题描述】:

我有一个带有沙盒属性的 iframe。此 iframe 的内容直接通过 'srcdoc' 属性设置。内容不安全,因为它可以由用户设置。

我想调整 iframe 的高度以匹配内容的高度。

var my_iframe = $(`<iframe sandbox frameborder=0 scrolling="no"></iframe>`);
var contained_html_code = `<h1>Example title</h1><p>Example paragraph</p>`;
my_iframe.prop('srcdoc', contained_html_code);

注意:

已经有很多这样的问题有很好的答案,但它们似乎都不适用于沙盒 iframe:我无法在 iframe 内执行任何脚本,而 iframe 外的脚本似乎无法执行访问和读取 iframe 的内容。如何使这个工作适用于沙盒 iframe?

奖励积分:

我只需要在设置 iframe 的内容时执行一次,但如果您知道如何编写不断更新大小的代码,这可能对遇到相同问题的其他人更有帮助。

背景/为什么我需要这个:

我网站的用户应该能够生成可以安全地显示给其他用户的任意样式的 html 消息。由于 html 可以包含不安全的脚本,因此这些消息被打包在 iframe 中。

【问题讨论】:

    标签: javascript html iframe sandbox


    【解决方案1】:

    你可以使用allow-same-origin沙盒属性而不需要allow-scripts

    $(function() {
        $("#testFrame").load(function() {
            $(this).height($(this).contents().height());
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <iframe id="testFrame" sandbox="allow-same-origin" srcdoc="<div style='height: 300px; background: red;'></div>">
    </iframe>

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 2012-11-27
      • 1970-01-01
      • 2014-03-06
      • 2021-07-17
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多