JavaScript 跳出 iframe 框架的方法详解

作者:闭包旅人时间:2026-10-31 07:51:05浏览:199

本文详细介绍如何利用 JavaScript 实现页面跳出 iframe 框架。主要方法包括使用 window.top 获取顶层窗口引用,以及通过 window.location 对象进行页面重定向。文章提供了具体的属性说明和代码示例,帮助开发者解决 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; //顶层窗口跳转到自身窗口
}

以上为 JavaScript 跳出 iframe 框架的详细内容,更多相关技术资料请查阅本站其他文章。

作者最新文章