JavaScript 跳出 iframe 框架

一、window.top

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

二、window.self

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

三、window.location

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

3.1 示例

window.location = 'https://blog.mazey.net/547.html'; //网站将跳转到后面的网址

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; //顶层窗口跳转到自身窗口
}

版权声明

本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者后除和本文原始地址:https://blog.mazey.net/547.html

(完)

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):