wec*_*sam 3 javascript firefox google-chrome
我需要知道是否window.close()真的要关闭窗口.这不是关闭窗口的重复- 如何确定窗口的打开方式?因为该解决方案依赖于检查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
Run Code Online (Sandbox Code Playgroud)
另一方面,如果用户在新选项卡中加载了包含此代码的页面:
console.log(window.opener); // also outputs null
window.close(); // doesn't work; window remains open
Run Code Online (Sandbox Code Playgroud)
然后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);
Run Code Online (Sandbox Code Playgroud)
但是,三秒钟的延迟会使我的应用程序对用户来说似乎很慢.那不行.在我的电脑上,延迟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");
}
Run Code Online (Sandbox Code Playgroud)
简而言之,我只需要在JavaScript中知道,无论是在调用之前还是之后window.close(),窗口是否会实际关闭.我怎么做?
只需打电话window.close(),然后检查window.closed它是否关闭.这也将捕获您尝试close()使用beforeunload处理程序的页面并且用户选择不让它关闭的情况....
哦,并且如果窗口将要关闭,则在返回之前同步window.close()更新每个规范更新window.closed,因此您不必担心超时等等.
| 归档时间: |
|
| 查看次数: |
995 次 |
| 最近记录: |