【问题标题】:Is Window Close-able?可以关闭窗口吗?
【发布时间】:2014-01-31 12:05:39
【问题描述】:

我需要知道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

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);

但是,延迟 3 秒会使我的应用程序在用户看来很慢。那不行。在我的电脑上,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() 之前或之后,窗口是否会真正关闭。我该怎么做?

【问题讨论】:

  • 为什么不直接打电话给window.close()改变位置?要么关闭,要么加载新网址。
  • 您可以轻松确定它是否关闭,但可能更难判断它是否会关闭...
  • @Pointy 实际上这是个好主意。

标签: javascript google-chrome firefox


【解决方案1】:

只需致电window.close(),然后检查window.closed 以查看它是否已关闭。这也将捕获您尝试使用 beforeunload 处理程序 close() 页面并且用户选择不让它关闭的情况......

哦,如果窗口将要关闭,window.close() 会在返回之前同步更新 window.closed,因此您不必担心超时等问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多