【问题标题】:How to prevent iframe from accessing parent window but allow parent window to access iframe document?如何防止 iframe 访问父窗口但允许父窗口访问 iframe 文档?
【发布时间】:2016-02-27 06:28:43
【问题描述】:

基本上,我想要这样的东西(它是 ES6):

<iframe id="iframe"></iframe>

<script>
  var iframeDoc = document.getElementById('iframe').contentDocument;
  iframeDoc.open('text/html', 'replace');
  iframeDoc.write(`
    <!doctype html>
    <html>
      <body>
        <script>
          // do not allow window.parent access!
          alert(window.parent.document.cookie);
        <\/script>
      </body>
    </html>
  `);
  iframeDoc.close();
</script>

警告框显示父窗口的 cookie,这是不好的。我希望 iframe 执行自己的沙盒 javascript 代码。这在 HTML5 中是否可行?

我已经尝试了sandbox 属性及其值的所有排列。

也许可以构造 iframe 并将其内容作为 src 属性的数据 URI,但这似乎有点 hacky。 (或者可能没有?URI长度没有限制吗?)

【问题讨论】:

    标签: javascript iframe


    【解决方案1】:

    您是否尝试过使用sandbox?

    W3C 对此有很好的文档,它会阻止顶级浏览上下文。

    http://www.w3schools.com/tags/att_iframe_sandbox.asp

    还可以查看本教程:

    http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

    【讨论】:

    • 是的,我在问题中提到我尝试使用sandbox,但它不允许我有特定要求(它可以双向阻塞,iframe 到父或父到 iframe ,但不仅仅是一个方向)。
    • 查看这篇博文,了解如何使用 JS 和沙箱实现这一目标。 benfrain.com/…
    • 更新了答案,发布了更好的博客。
    • 那篇博文似乎更多地是关于沙盒 CSS 而不是 JS。它不会阻止 iframe javascript 访问父窗口。
    • 该帖子的要点以及我刚刚发布的 HTML5Rocks 是您可以与沙盒 iframe 进行通信。有多种方法。 HTML5 是使用信使传递内容的更好示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 2018-12-18
    • 1970-01-01
    • 2011-10-25
    • 2015-07-16
    • 1970-01-01
    • 2015-12-26
    相关资源
    最近更新 更多