禁止iframe显示页面

Disallow iframes from displaying page

本文关键字:显示 iframe 禁止      更新时间:2023-09-26

如何禁止人们在iframe中使用我的页面?是否可以只使用HTML或必须使用JavaScript/jQuery。

有几种不同的方法可以解决这个问题,这些方法在"破坏框架破坏"的论文中有详细的解释,如果你有机会的话,我强烈建议你阅读。

前两个选项是使用HTTP头,它不使用任何HTML, JavaScript/jQuery,但确实需要在web服务器上配置。

  1. 使用X-FRAME-OPTIONS标头

    • X-FRAME-OPTIONS: deny -帧内无渲染
    • X-FRAME-OPTIONS: sameorigin -如果原点不匹配则不渲染
  2. Content-Security-Policy头允许您使用frame-ancestors指令指定允许哪些原点将页面嵌入到框架或iframe中。这样做的缺点是它没有提供一种执行侧宽策略的方法。

    • Twitter的CSP Content-Security-Policy: frame-ancestors *.twitter.com;示例
    • 这是浏览器兼容性- http://caniuse.com/contentsecuritypolicy

EDIT: frame-ancestors实际上是内容安全策略级别2的一部分,其兼容性可以在这里看到

建议的方法是在页面顶部使用以下代码片段。如果你的页面是框架的,它会隐藏你的内容,否则会显示内容。

<style> html {display:none;} </style>
<script>
   if (self == top) {
       document.documentElement.style.display = 'block'; 
   } 
   else {
       top.location = self.location; 
   }
</script>

使用break out of iframe脚本:

<script type="text/javascript">
        if (top.location != self.location) {
            top.location = self.location.href;
        }
</script>