防止网页被Frame,方法有很多种;
方法一:常见的比如使用js,判断顶层窗口跳转:
1 2 3 4 5 |
(function () { if (window != window.top) { window.top.location.replace(window.location); //或者干别的事情 } })(); |
一般这样够用了,但是有一次发现失效了,看了一下人家网站就是顶层窗口中的代码,发现这段代码:
1 2 |
var location = document.location; // 或者 var location = ""; |
轻轻松松被破解了,悲剧。
注:此方式破解对IE6,IE7,IE9+、Chrome、firefox无效; 感谢@genify和@_Franky 补充斧正。
方法二:meta 标签:基本没什么效果,所以也放弃了:
1 |
<meta http-equiv="Windows-Target" contect="_top"> |
方法三:使用HTTP 响应头信息中的 X-Frame-Options属性
使用 X-Frame-Options 有三个可选的值:
- DENY:浏览器拒绝当前页面加载任何Frame页面
- SAMEORIGIN:frame页面的地址只能为同源域名下的页面
- ALLOW-FROM:origin为允许frame加载的页面地址
绝大部分浏览器支持:
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 4.1.249.1042 | 3.6.9 (1.9.2.9) | 8.0 | 10.5 | 4.0 |
具体的设置方法:
Apache配置:
1 |
Header always append X-Frame-Options SAMEORIGIN |
nginx配置:
1 |
add_header X-Frame-Options SAMEORIGIN; |
IIS配置:
1 2 3 4 5 6 7 8 9 10 11 |
<system.webServer> ... <httpProtocol> <customHeaders> <add name="X-Frame-Options" value="SAMEORIGIN" /> </customHeaders> </httpProtocol> ... </system.webServer> |
具体可以查看: