2014-01-12 171 views
3

我需要知道window.close()是否確實要關閉該窗口。這不是Close window - How to determine how window was opened?的重複,因爲該解決方案依賴於檢查window.name,這不完全是萬無一失的;彈出窗口可以打開一個不同的名字,但仍然可以通過window.close()關閉。窗戶是否可以關閉?

我不能只檢查window.opener是否定義或不爲空,因爲在Firefox和Chrome中,如果用戶關閉了開啓器,window.opener設置爲null。例如:

// In parent window: 
window.open(); 

// In child window: 
console.log(window.opener); // outputs a Window object 

// Now, click the X on the parent window. 

// Continue below in child window: 
console.log(window.opener); // outputs null 
// However, you can still close the window! 
window.close(); // closes the child window 

在另一方面,如果用戶在新標籤裝入該代碼的頁面:

console.log(window.opener); // also outputs null 
window.close(); // doesn't work; window remains open 

火狐則抱怨在控制檯有關的腳本不能夠錯誤關閉窗口沒有被腳本打開,並且Chrome什麼都不做。

,我需要檢查window.close()是否會關閉窗口的原因是,如果窗口保持打開狀態,我想要去到另一個地址。我想這樣做:

// Try to close window. 
window.close(); 
// If the window is still open after three seconds, go to another page. 
setTimeout(function(){ 
    // For testing purposes: 
    alert("Not closed!"); 
    // What I want to do: 
    window.location = "http://www.example.com/"; 
}, 3000); 

但是,三秒滯後將使我的應用程序看起來對用戶來說很慢。那不會。在我的電腦上,1毫秒的延遲足以讓窗戶關閉;只有在窗口保持打開的情況下才會發出警報。但是,我需要有人確認所有計算機都是如此。這也不起作用:

try{ 
    // This will not throw an error regardless of 
    // whether the window was actually closed: 
    window.close(); 
}catch(e){ 
    // This never happens: 
    console.log("Could not close window"); 
} 

總之,我只需要在JavaScript的方式來了解,之前或致電window.close()後,窗口是否會真正關閉。我怎麼做?

+0

爲什麼不就叫'window.close()的'*和*也改變位置?它會關閉,或者它會加載新的URL。 – Pointy

+0

你可以很容易地確定它是否確實接近,但它可能是很難判斷它會關閉...... – dandavis

+0

@Pointy這是個好主意,實際上。 – wecsam

回答

8

只要打電話window.close(),然後檢查window.closed,看它是否關閉。這也將趕上情況下,您嘗試close()在網頁的beforeunload處理程序和用戶選擇不讓它接近....

哦,按規格window.close()同步如果窗口將會返回前更新window.closed關閉,所以你不必擔心超時和什麼。

相關問題