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?

时间秒杀一切 提交于 2019-11-28 08:25:08

问题


Basically I want to have an iFrame which always restricts it's content as if it comes from a different domain, even if the content comes from the same origin.

Is there any way to do this?


回答1:


This will hide window.parent in the child frame/window, but not the top property.

BUT the window.parent property is STILL accessible till the end of the onload event of the child window/frame.

<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>



回答2:


The best solution is probably to use the HTML5 sandbox attribute on the iframe, which (by default) explicitly disables both scripting and same-origin access to the parent DOM.

Good introduction at http://msdn.microsoft.com/en-us/hh563496.aspx

As of Dec 2012, this seems to be supported on most current browsers.



来源:https://stackoverflow.com/questions/13247798/how-can-i-prevent-javascript-in-an-iframe-to-access-properties-of-the-outer-site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!