zoukankan      html  css  js  c++  java
  • 防止网页被嵌入框架

    有这样一种情况,你的网页a被网站b恶意嵌入iframe,用户看到的是你的网页内容,但是不知道网站来自于b,这就可能做一些坏事,比如误导用户跳转其他。。网址

    通过一段js代码解决这个问题:

    <script type="text/javascript">
    
    if (window!=top) // 判断当前的window对象是否是top对象
    
    top.location.href =window.location.href; // 如果不是,将top对象的网址自动导向被嵌入网页的网址
    
    </script>
    

     

    但实际有一个问题:使用后,任何人都无法再把你的网页嵌入框架了,包括你自己在内

    于是对代码进行一个升级:

    if (top.location.hostname != window.location.hostname) {
    
      top.location.href = window.location.href;
    
    }
    

     此代码报错,网站跨域了,对跨域站点操作就会报错

    于是,换一种思路,网站报错了,那就是跨域了呗,也就是呗=被其他网站框架嵌套了

    try{
      top.location.hostname;
    }
    
    catch(e){
      top.location.href = window.location.href;
    }
    

    又出现问题,在chrome里面,跨域竟然没有报错

    于是增加对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;
    
    }
    

      

  • 相关阅读:
    nginx基本命令
    一堆LCT板子
    17?17!
    ……妈妈我会写维修数列了!
    bzoj3744 Gty的妹子序列
    Noip2016 总结&反思
    bzoj4025 二分图
    [SHOI2008]堵塞的交通traffic
    bzoj4237 稻草人
    BestCoder Round #90
  • 原文地址:https://www.cnblogs.com/liuxiaoru/p/13686124.html
Copyright © 2011-2022 走看看