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


    相信大家网上也见过很多类似的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;

    }



    判断两个页面的域名是否相同,思路是正确的,但是结果却报错,IE把这种错误叫做"没有权限"。也就是

    说,浏览器甚至不允许你查看top.location.hostname,跨域情况下,一看到这个对象,就直接报错了。
    没办法,只好扑捉异常进行判断了,代码如下:
    try{
      top.location.hostname;
    }
    catch(e){
      top.location.href = window.location.href;
    }

    以上代码经测试在IE和Firefox中可以正确运行。但是,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;
    }


    至此,兼容所有,功能ok,除过你自己的域名外,其他域名一律无法将你的网页嵌入框架。

    //成功一定有方法,失败一定有原因。
  • 相关阅读:
    HttpServlet
    Servlet练习和自定义GenericServlet实现类
    Servlet-ServletRequest
    HTTP协议-GET/POST请求
    Servlet-ServletConfig对象
    Servlet
    1089. Duplicate Zeros
    1002. Find Common Characters
    17. Letter Combinations of a Phone Number
    254. Factor Combinations
  • 原文地址:https://www.cnblogs.com/webapi/p/2415306.html
Copyright © 2020-2023  润新知