防止网页被嵌入框架的代码

if(window!=top){  //判断当前对象是否为top对象

  top.location.href=window.location.href;   //若不是,将对象的网址自动导向被嵌入的网址地址

};

缺点:所有的无法再把你的网址去潜入框架包括在自己。

 

if (top.location.hostname != window.location.hostname) {

  top.location.href = window.location.href;

}

这个方案看是可以,这是有个问题会导致if判断里会报错——跨域。

top.location.hostname 是 www.a.com,而 window.location.hostname 是 www.b.com。也就是说,a.com把b.com嵌入了它的网页中。这时,比较 top.location.hostname != window.location.hostname 浏览器会提示代码出错!

 

只要查看top.location.hostname是否报错就可以了。如果报错了,表明存在跨域,就对top对象进行URL重导向;如果不报错,表明不存在跨域(或者未使用框架),就不采取操作。

try{

  top.location.hostname;

}

catch(e){

  top.location.href = window.location.href;

}

这样写已经正确了,在IE和Firefox中可以正确运行。但是,Chrome浏览器会出现错误,不知为何,在跨域情况下,Chrome对top.location.hostname不报错!

没办法,只能为了Chrome,再加一段补充代码。

try{

  top.location.hostname;

  if (top.location.hostname != window.location.hostname) {

    top.location.href =window.location.href;

  }

}

catch(e){

  top.location.href = window.location.href;

}

好了,升级版代码完成。除了本地域名以外,其他域名一律无法将你的网页嵌入框架。

原文:http://www.ruanyifeng.com/blog/2010/08/anti-frameset_javascript_codes_continued.html

posted @ 2016-03-06 13:52  秋虹连宇  阅读(393)  评论(0编辑  收藏  举报