如何禁止人们在 iframe 中使用我的页面。是否可以仅使用 HTML 或我必须使用 JavaScript/jQuery。
最佳答案
有几种不同的方法可以解决这个问题,在 Busting Frame Busting paper 中有详细解释。如果有机会,我强烈建议您阅读。
前两个选项使用 HTTP header ,它不使用任何 HTML、JavaScript/jQuery,但需要在您的 Web 服务器上进行配置。
使用
X-FRAME-OPTIONS
header 。X-FRAME-OPTIONS: deny
- 帧内不渲染X-FRAME-OPTIONS: sameorigin
- 如果原点不匹配则不渲染
Content-Security-Policy
header 允许您使用frame-ancestors
指令 指定允许哪些来源将页面嵌入到框架或 iframe 中。这样做的缺点是它没有提供一种方法来执行广泛的政策。- Twitter 的 CSP 示例
Content-Security-Policy: frame-ancestors *.twitter.com;
- 这是浏览器兼容性 - http://caniuse.com/contentsecuritypolicy
- Twitter 的 CSP 示例
编辑:frame-ancestors
实际上是 Content Security Policy Level 2 的一部分为此 compatibility can be seen here
建议的方法是在页面顶部使用以下代码片段。如果它是 iframed,它会隐藏您的页面内容,否则会显示内容。
<style> html {display:none;} </style>
<script>
if (self == top) {
document.documentElement.style.display = 'block';
}
else {
top.location = self.location;
}
</script>
关于javascript - 禁止 iframe 显示页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23437123/