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

Dec*_*oon 5 javascript iframe

基本上,我想要这样的东西(它是 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>
Run Code Online (Sandbox Code Playgroud)

警报框显示父窗口的 cookie,这是错误的。我希望 iframe 执行它自己的沙盒 javascript 代码。这在 HTML5 中甚至可能吗?

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

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

Mun*_*der 0

你尝试过使用sandbox吗?

W3C 有关于此的非常好的文档,它将阻止顶级浏览上下文。

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

另请查看本教程:

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