也是第一次用这个标签 嵌套其他网站有的跳转了 本以为是自己的问题 百度才得知 是其他网站 有如下代码
if (top.location != self.location) {top.location=self.location;}
会自动判断当前的location是否是顶层的,即是否被嵌套到iframe里面了,如果是,则强制跳转。
解决办法有两个
- 双重iframe:
双重iframe的确可以阻止强制跳转。但是,第一层的iframe就覆盖了第二层的。所以要把第一层的做成透明的,然后第二层嵌套该嵌套的网页。
- 增加标签属性
security="restricted"
sandbox=""
security="restricted"
是IE的禁止js的功能,会导致其他js方法跳转不成功
sandbox=""
是H5的功能。可以让IE,Chrome,Firefox这三大浏览器都实现了禁止iframe的自动跳转
<iframe
security="restricted" sandbox=""
src="https://blog.csdn.net/chuan0106"/>
而我的做法是 判断 url 地址是否 === 会跳转的url 如果是就使用该两个方法
当前URL地址=== 会跳转的URL地址 ? <iframe security="restricted" sandbox=""
frameBorder="0" src={URL地址} /> : <iframe frameBorder="0" src={URL地址} />
防止自己的网站被别人 iframe
嵌套
在head位置中添加该代码
<head>
<script language="javascript">
if (top.location != location)
{
top.location.href = location.href;
}
</script>
</head>
或者
<head>
<script language="javascript">
if(self!=top){
top.location.href=self.location.href;}
</script>
</head>
这种如果别人嵌套了你的网站 就会自动跳转到你的网站 而非嵌套
但是 当别人用类似下面代码做iframe
嵌套调用时,会躲避你的javascript代码。
伪代码:
<iframe src="你的页面地址" 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[0].location.href="";
</script>
更好的解决办法
这里赋值为空页面,也可赋值为你的页面的URL地址.
js 解决
if(top != self){
location.href = "about:blank";
}
另外一种屏蔽iframe
方法
html 解决
header("X-Frame-Options: deny");
header("X-XSS-Protection: 0");