如何在页面加载期间发现我的页面作为框架嵌入到其他站点?我想推荐人请求标头在这里帮不了我?谢谢。
9 回答
您无法从服务器端检查它,但您可以在页面加载后使用 javascript 来检测它。比较top
和self
,如果它们不相同,你就在一个框架中。
此外,一些现代浏览器尊重X-FRAME-OPTIONS
标头,它可以有两个值:
- DENY - 如果页面包含在框架中,则防止页面被呈现
- SAMEORIGIN – 与上面相同,除非页面与顶级框架集持有者属于同一域。
用户包括不能嵌入框架的 Google 的 Picasa。
支持标头的浏览器,最低版本:
- IE8 和 IE9
- 歌剧 10.50
- 野生动物园 4
- 铬 4.1.249.1042
- Firefox 3.6.9(带有NoScript的旧版本)
Stackoverflow 包含一些 JS 来测试它(master.js
)。这是它的相关部分:
if(top!=self){
top.location.replace(document.location);
alert("For security reasons, framing is not allowed; click OK to remove the frames.")
}
但请记住,可以禁用 JS。
对于现代浏览器,您可以使用标准 CSP(内容安全策略)。以下标题将阻止文档加载到任何地方的框架中:
Content-Security-Policy: frame-ancestors 'none'
(不过,IE 11 需要X-
前缀)。您还可以更改'none'
为允许框架的来源,例如您自己的网站。
为了涵盖较旧的浏览器,最好与@Maerlyn's answer一起使用。
您可以使用 javascript 阻止在 iframe 中加载您的页面
<script type="text/javascript">
if ( window.self !== window.top ) {
window.top.location.href=window.location.href;
}
</script>
此代码将您页面 iframe 的容器地址更改为您的页面地址并强制容器显示您的页面。
或者,如果您不介意某些位置的内容但不希望在某个站点上显示该内容,则可以阻止特定域。例如,如果offendingdomain.com
要嵌入您的内容,您可以这样做:
<script type="text/javascript">
if(document.referrer.indexOf("offendingdomain.com") != -1) {
window.location = "http://www.youtube.com/watch_popup?v=oHg5SJYRHA0";
}
</script>
这将检查父文档的位置,看看它是否offendingdomain.com
是嵌入您的内容的。然后,此脚本会将 iframe 发送到某个著名的 youtube 视频作为惩罚。实际上,他们只是 Rick-Rolled 自己。
使用 javascript 检查是否已在 iframe 上加载,方法是将以下脚本放在 php 文件的末尾,然后重定向到显示警告或注意不应使用 iframe 加载页面的页面。
<script type="text/javascript">
if(top.location != window.location) {
window.location = '/error_iframe.php';
}
</script>
<?php
header("Content-Security-Policy: frame-ancestors 'none'");
?>
将 hosname 替换为域名
if (window.top.location.host != "hostname") {
document.body.innerHTML = "Access Denied";
}
我在标题顶部使用此 PHP 代码
if($_SERVER['SERVER_NAME'] != 'yourwebsite.com'){
header('location: yourwebsite.com');
}
如果有人为您的网站添加了 iframe,它将重定向到您的网站