happyxp 发表于 2020-11-16 17:30:36

如何防止自己的网页被别人iframe嵌入

前面说了如何阻止 iframe里引用的网页自动跳转,已达到iframe页面的目的。
这次讲一下如何防止自己的网页被别人iframe。

1、这些方法都可行,但不是太可靠。
<script language="javascript">
if( top.location != self.location) top.location.href=self.location.href;
</script>或
<script language="javascript">
if (top.location != location) top.location.href = location.href;
</script>或
<script language="javascript">
if (top.location != self.location) {top.location=self.location;}
</script>或
<script language="javascript">
if (top.frames.length!=0) top.location=self.document.location;
</script>不可靠的原因:
当别人用如下类似代码做IFRAME嵌套调用时,就可能躲过你的页面的javascript代码。
<iframe src="http://xp6.org/" name="tv" marginwidth="0" marginheight="0" scrolling="No" noResize frameborder="0" id="tv"framespacing="0" width="580" height="550" VSPACE=-145 HSPACE=-385></iframe>
<script language="javascript">
var location="";
var navigate="";
frames.location.href="";
</script>或
<iframe src="http://xp6.org/" class="t-iframe" scrolling="no" security="restricted" sandbox="">或

<script type="text/javascript" charset="utf-8">
document.write('<iframe seamless sandbox security="restricted" id="url_mainframe" frameborder="0" scrolling="yes" name="main" src="http://xp6.org/" style="height:100%; visibility: inherit; width: 100%; z-index: 1;overflow: visible;"></iframe>');
</script>2、代码层次的屏蔽,方法可行,但不是很人性化。
Meta标签方法
<meta http-equiv="X-FRAME-OPTIONS" content="DENY">PHP方法
<?php header('X-Frame-Options:Deny'); ?>Apache主机方法
Header always append X-Frame-Options SAMEORIGINNginx主机方法
add_header X-Frame-Options "SAMEORIGIN";
.htaccess方法
在网站根目录下的.htaccess文件中中加一句
Header append X-FRAME-OPTIONS "SAMEORIGIN"
IIS方法
在web.config文件中加<system.webServer>
...
<httpProtocol>
    <customHeaders>
      <add name="X-Frame-Options" value="SAMEORIGIN" />      
    </customHeaders>   
</httpProtocol>
...
</system.webServer>
之所以说不人性化,是因为这样操作之后,别人iframe会显示服务器拒绝之类的信息,虽然是屏蔽了,但是自己网站也不能宣传了。

3、推荐解决方法。
<script language="javascript">
if(top != self){
    location.href = "http://xp6.org/iframe.html";
    top.location.href=self.location.href;
}
</script>
将上面的代码复制到需要屏蔽页面<head>里面加载。
制作一个iframe.html页面里面放张网站宣传图片,加个链接,放到网站根目录。
原理:
第一步直接强制访问咱自己设定的iframe.html页面,如果网站禁用了JS跳转,那么执行到这一步就结束了,这样即使他们iframe了咱的网站,看到的只是咱的图片宣传页。
第二步,如果没有禁用JS,那么会接着执行top.location.href=self.location.href; ,然后跳转到我们的网址页面。
目前测试这种方法没什么问题。

页: [1]
查看完整版本: 如何防止自己的网页被别人iframe嵌入