如何检查JavaScript中的窗口是否已关闭?

时间:2013-05-16 06:49:50

标签: javascript jquery events javascript-events

例如,我有这样的JavaScript:

 windowHandle = window.open('http://www.irt.org/','testWindow','height=200,width=200');

我想检查'testWindow'是否已关闭,如果是,则运行一个函数。

我已经用Google搜索了这个问题,但到目前为止我发现的只有:

if (testWindow.close) {..}

只运行一次。所以我想知道窗口关闭时是否触发了事件?感谢。

3 个答案:

答案 0 :(得分:1)

我会使用灯箱而不是window.open来执行此类任务。大多数情况下,将用户嵌入您的网站会更好,特别是如果您正在执行类似上传的操作。

我过去曾使用colorbox执行类似的任务。这是一个链接http://www.jacklmoore.com/colorbox/

然后你只需将回调附加到colorbox的已关闭事件

答案 1 :(得分:0)

实际上,您可以在MDN best practices

中找到更好的实施方案
  

来自MDN的代码段

var windowObjectReference = null; // global variable

function openFFPromotionPopup() {
  if(windowObjectReference == null || windowObjectReference.closed)
  /* if the pointer to the window object in memory does not exist
     or if such pointer exists but the window was closed */

  {
    windowObjectReference = window.open("http://www.spreadfirefox.com/",
   "PromoteFirefoxWindowName", "resizable,scrollbars,status");
    /* then create it. The new window will be created and
       will be brought on top of any other window. */
  }
  else
  {
    windowObjectReference.focus();
    /* else the window reference must exist and the window
       is not closed; therefore, we can bring it back on top of any other
       window with the focus() method. There would be no need to re-create
       the window or to reload the referenced resource. */
  };
}

通过这种方式,您可以可靠地确定窗口是否关闭。

希望这有帮助

答案 2 :(得分:0)

对于文件上传,您可能想要尝试隐藏的iframe黑客,而不是单独的窗口。或者上面是Matthew Bucci建议的灯箱。