【问题标题】:How can I prevent JavaScript in an iFrame to access properties of the outer site, even if the iFrame's content comes from the same origin?如何防止 iFrame 中的 JavaScript 访问外部站点的属性,即使 iFrame 的内容来自同一来源?
【发布时间】:2012-10-26 05:09:38
【问题描述】:

基本上我想要一个 iFrame,它总是限制它的内容,就好像它来自不同的域一样,即使内容来自同一个来源。

有什么办法吗?

【问题讨论】:

  • 您可能想看看CajaAdSafe。它们为“guestcode”提供了一个包装器,以防止它们做诸如弄乱您的全局对象之类的事情。

标签: javascript iframe same-origin-policy


【解决方案1】:

最好的解决方案可能是在 iframe 上使用 HTML5 沙盒属性,它(默认情况下)显式禁用脚本和对父 DOM 的同源访问。

http://msdn.microsoft.com/en-us/hh563496.aspx的好介绍

截至 2012 年 12 月,这似乎是 supported on most current browsers

【讨论】:

    【解决方案2】:

    这将在子框架/窗口中隐藏window.parent,但不会隐藏top 属性。

    但是在子窗口/框架的 onload 事件结束之前,window.parent 属性仍然可以访问。

    <html>
      <head>
        <style type="text/css">
          #wrapper {width:1000px;height:600px;}
        </style>
        <script type="text/javascript">
          window.onload = function() {
            var frm = document.getElementById('childFrame');
            var win = frm.contentWindow || (frm.contentDocument && frm.contentDocument.parentWindow) || (frm.document && frm.document.parentWindow);
            if (win) win.parent = null;
          }
        </script>
      </head>
      <body>
        <div id="wrapper">
          <iframe id="childFrame" src="child.html" frameborder="0" style="width:100%;height:100%;"></iframe>
        </div>
      </body>
    </html>
    

    【讨论】:

    • 这对我来说似乎不太安全。如果在子 iframe 中的任何位置存在对父窗口的任何挥之不去的引用,它们就会泄露出去,而您只会有安全的错觉。
    • 还有top,与parent不同,不能重新定义。
    猜你喜欢
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    相关资源
    最近更新 更多