一、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

(完)