防止网页被嵌入iframe

2026-05-02 12:25:38 169
分类:Web前端

防止网页被嵌入iframe,简单的两句代码就能实现

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

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

如果自己的网页嵌入自己的框架

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;

}

然而事情并没有这么简单,

如果iframe动态加载,而且禁止了js代码运行,上面的代码完全失效

document.write('<iframe seamless sandbox security="restricted" id="url_mainframe" frameborder="0" scrolling="yes" name="main" src="http://www.pinbu.cc/3383-1.html" style="height:100%; visibility: inherit; width: 100%; z-index: 1;overflow: visible;"></iframe>');

为了彻底防止别人用IFRAME框架嵌套调用自己的网页,最有效的手段是从后端做手脚。

比如在web服务器或者php代码里加入header(‘X-Frame-Options:Deny');表示不能被嵌入到任何iframe或frame中。