在页面中获取iframe中window对象,在iframe中获取上级window对象

本文详细介绍了如何在页面中操作iframe的window对象,判断是否处于iframe中,以及跨iframe通信的方法。同时探讨了防止页面被嵌入iframe以及针对不同情况下的iframe嵌套控制策略。
摘要由CSDN通过智能技术生成

1 在页面中获取iframe中window对象

const iframe=document.getElementById("myiframe")
iframe.contentWindow    获取iframe中的window对象  
iframe.contentDocument  获取iframe中的document对象

2 在iframe中获取上级window对象

window.parent 获取上一级的window对象
window.top 获取最顶级容器的window对象

3 判断是否在iframe中

//方式一 
if (self.frameElement && self.frameElement.tagName == "IFRAME") { 
  console.log('in iframe'); 
} 
//方式二 
if (window.frames.length != parent.frames.length) { 
  console.log('in iframe中'); 
} 
//方式三 
if (self != top) { 
  console.log('in iframe中'); 
}

4 通信

主页面监听:

//主页面
window.addEventListener('message',function(event){
  const data = event.data;
  // 判断域名
  if(event.origin == 'http://127.0.0.1'){
   //doSomething()
  }

})

iframe中发送消息

   const iframe = ocument.getElementById("myiframe");
   iframe.contentWindow.postMessage(data, "*");

5 禁止页面被其他页面iframe

  // 方式一
  if(top.location != location) { 
      top.location.href = location.href; 
  }
  // 方式二
  if(self!=top){
    top.location.href=self.location.href;
  }

6 破解第5点进行iframe嵌套

<iframe src="你的页面地址" name="frame" marginwidth="0" marginheight="0" scrolling="No" noResize frame id="frame" framespacing="0"
    width="600" height="800"></iframe>
<script language="javascript"> 
    const location = ""; 
    const navigate = ""; 
    frames[0].location.href = "";
 </script>

7 阻止第6点,不允许iframe嵌套

// 这种方式会禁止所有的页面的嵌入,本域名内的页面嵌入也会被禁止
if(top != self){ 
 location.href = "about:blank"; //可设置为自己的URL
} 

8 拓展第7点,允许自己域名iframe嵌套

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;
}
  • 19
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值