如何防止 iframe 访问父窗口,但允许父窗口访问 iframe 文档

How to prevent iframe from accessing parent window but allow parent window to access iframe document?

本文关键字:访问 iframe 窗口 许父 文档 何防止      更新时间:2023-09-26

基本上,我想要这样的东西(它是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,但这似乎有点笨拙。(或者也许不是?URI 长度没有限制吗?

你试过使用 sandbox 吗?

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

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

另请查看本教程:

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