窗户能够关闭吗?

时间:2014-01-12 19:53:44

标签: javascript google-chrome firefox

我需要知道window.close()是否真的要关闭窗口。这不是Close window - How to determine how window was opened?的重复,因为该解决方案依赖于检查window.name,这并非完全万无一失;弹出窗口可以使用其他名称打开,但仍可通过window.close()关闭。

我无法检查window.opener是否已定义为null,因为在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

Firefox然后在错误控制台中抱怨脚本无法关闭脚本未打开的窗口,而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()之前或之后知道窗口是否会实际关闭。我该怎么做?

1 个答案:

答案 0 :(得分:9)

只需致电window.close(),然后检查window.closed以查看是否已关闭。这也会遇到你尝试close()一个带有beforeunload处理程序的页面并且用户选择不让它关闭的情况....

哦,并且如果窗口即将关闭,每个规范window.close()会在返回之前同步更新window.closed,因此您不必担心超时等等。