防止网页被Frame,方法有很多种;
方法一:常见的比如使用js,判断顶层窗口跳转:
js 代码:
(function(){
if(window != window.top){
window.top.location.replace(window.location);//或者干别的事情
}
})();
一般这样够用了,但是有一次发现失效了,看了一下人家网站就是顶层窗口中的代码,发现这段代码:
js 代码:
var location = document.location;
// 或者 var location = "";
轻轻松松被破解了,悲剧。
注:此方式破解对IE6,IE7,IE9+、Chrome、firefox无效; 感谢@genify和@_Franky 补充斧正。
方法二:meta 标签:基本没什么效果,所以也放弃了:
html 代码:
<metahttp-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配置:
html 代码:
Header always append X-Frame-Options SAMEORIGIN
nginx配置:
html 代码:
add_header X-Frame-Options SAMEORIGIN;
IIS配置:
html 代码:
<system.webServer>
...
<httpProtocol>
<customHeaders>
<addname="X-Frame-Options"value="SAMEORIGIN"/>
</customHeaders>
</httpProtocol>
...
</system.webServer>