码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript跳出iframe框架

时间:2017-07-13 12:41:21      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:click   htm   elf   pat   path   add   func   顶层窗口   org   

一、window.top

top属性返回最顶层的先辈窗口。

该属性返回对一个顶级窗口的只读引用。如果窗口本身就是一个顶级窗口,top属性存放对窗口自身的引用。如果窗口是一个框架,那么top属性引用包含框架的顶层窗口。

二、window.self

self属性可返回对窗口自身的只读引用。等价于Window属性。

三、window.location

window.location(MDN)对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。

3.1 示例

window.location = ‘http://www.mazey.net/‘; //网站将跳转到后面的网址

3.2 属性

  • location.hostname返回web主机的域名
  • location.pathname返回当前页面的路径和文件名
  • location.port返回web主机的端口(80或443)
  • location.protocol返回所使用的web协议(http://或https://)

四、iframe示例

<h1>iframe 1</h1>
<button type="button" id="self">Show Self</button>
<button type="button" id="selflocation">Show Self Location</button>
<button type="button" id="selfhref">Show Self Href</button>

<button type="button" id="top">Show Top</button>
<button type="button" id="toplocation">Show Top Location</button>
<button type="button" id="tophref">Show Top Href</button>

<button type="button" id="replace">Replace Me To Whole Page</button>

<script>
document.getElementById(‘self‘).addEventListener(‘click‘, function(){
    alert(window.self);
});
document.getElementById(‘selflocation‘).addEventListener(‘click‘, function(){
    alert(window.self.location);
});
document.getElementById(‘selfhref‘).addEventListener(‘click‘, function(){
    alert(window.self.location.href);
});

document.getElementById(‘top‘).addEventListener(‘click‘, function(){
    alert(window.top);
});
document.getElementById(‘toplocation‘).addEventListener(‘click‘, function(){
    alert(window.top.location);
});
document.getElementById(‘tophref‘).addEventListener(‘click‘, function(){
    alert(window.top.location.href);
});

document.getElementById(‘replace‘).addEventListener(‘click‘, function(){
    if(window.top !== window.self){
        window.top.location.href = window.self.location.href;
        console.log(‘You replace successfully!‘);
    }else{
        console.log(‘You don\‘t need replace, i\‘m top!‘);
    }
});
</script>

五、总结

若想页面跳出iframe在里面加上下面这段代码即可。

if(window.top !== window.self){ //若自身窗口不等于顶层窗口
    window.top.location.href = window.self.location.href; //顶层窗口跳转到自身窗口
}

JavaScript跳出iframe框架

JavaScript跳出iframe框架

标签:click   htm   elf   pat   path   add   func   顶层窗口   org   

原文地址:http://www.cnblogs.com/mazey/p/7159720.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!