JavaScript跳出iframe框架

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章