HTML框架(iframe )限制

HTML框架(iframe )进行限制。很多人喜欢HTML框架(iframe )来加载他人的网页,加载他人的服务器宽带。

要求:

  1、防止自己网站被他人iframe 内联框架使用

  2、如果自己网站是可以用iframe 内联框架

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

 

上的代码只能实现判断使用内联框架,如果自己使用的话,也会被跳转,那么就有了下面的代码:

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;
}

 

下面的代码是案例:

 

下面是a页面,嵌套b页面。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>a页面</title>
    <style type="text/css" media="screen">
        * {
            padding: 0;
            margin: 0;
            border: none;
        }
    </style>
</head>
<body>
    <iframe src="http://w3cku.cn/test/b_iframe.html"></iframe>
</body>
</html>

 

 

下面是b页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我是b页面</title>
    <style type="text/css" media="screen">
        * {
            padding: 0;
            margin: 0;
            border: none;
        }
    </style>
</head>
<body>
        <div>我是b页面</div>
    <script type="text/javascript">
        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;
        }
    </script>
</body>
</html> 

案例:

来源于:http://www.ruanyifeng.com/blog/2008/10/anti-frameset_javascript_codes.html

posted @ 2017-05-03 17:07  码农-金  阅读(3737)  评论(0)    收藏  举报