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嵌套
top.location.hostname;
if (top.location.hostname != window.location.hostname) {
top.location.href =window.location.href;
}
}
catch(e){
top.location.href = window.location.href;
}
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;
}