检查浏览器窗口是否关闭

Check browser window closed

本文关键字:是否 窗口 浏览器 检查      更新时间:2023-09-26

我有一个网页,上面有一个打开另一个窗口的按钮。

当点击按钮并打开新页面时,我会禁用该按钮(因为点击按钮只需要打开一个页面)。我使用window.open()而不是windows.showModalDialog(),因为用户应该同时处理这两个页面。

当第二页关闭时,我必须重新启用第一页中的按钮。

我试过这样的东西:

var win = window.open("SecondPage.htm");
// disable button        
while (!win.closed) {
    setTimeout('', 2000);
}
// re-enable button

但是使用while循环会减慢浏览器的速度,所以实际上不可能在第一页上工作。。。

有更好的办法解决我的问题吗?

setTimeout('', 2000)

不是sleep()

while循环一直在转动,确实会消耗掉所有的CPU,从而降低浏览器的速度。

更好:

var win = window.open("SecondPage.htm");
// disable button        
setTimeout('enableButtonIfWindowClosed', 2000);
function enableButtonIfWindowClosed {
  if (windowClosed()) {
    enableButton();
  }
  else {
    setTimeout('enableButtonIfWindowClosed', 2000);
    //function recalls the function itself
  }
}

我想您可以将事件绑定到unloadbeforeunload事件:

win.onunload = function() {
    // re-enable button
};

但是,如果用户在窗口中加载了不同的页面,也会调用此函数,因此您仍然希望在事件处理程序中检查win.closed

如果您通过javascript处理,用户将刷新页面1。这将失败。所以当使用点击第2页的链接时,让ajax调用保存在服务器中的按钮被禁用,并让按钮的属性像一样

        //page 1 script
   var win = null;     
$("#link1").click(function(){
  $("#button_id").attr("disabled", "disabled");        
  //ajax to server and save like button1 is disabled
  win = window.open("URL2");
  win.onunload = function () {
    //enable the button 1
  }      
});

  //In the page 2 script
  window.unload = function() {
    //ajax to button is enabled
  }

这个Konerak的代码不能解决CPU和内存浪费问题。当使用setTimeout时,您也必须使用clearTimeout(),否则只要顶部窗口打开,计时器就会抽搐。修复代码如下:

var win = window.open("SecondPage.htm");
var delay;
// disable button        
delay=setTimeout('enableButtonIfWindowClosed', 2000);
function enableButtonIfWindowClosed {
  if(delay) clearTimeout('delay');
  if (windowClosed()) {
    enableButton();
  }
  else {
    setTimeout('enableButtonIfWindowClosed', 2000);
    //function recalls the function itself
  }
}

更复杂的:

var win = window.open("SecondPage.htm");
var delay;
// disable button
delay=setInterval('enableButtonIfWindowClosed', 2000);
function enableButtonIfWindowClosed {
  if (windowClosed()) {
    if(delay) clearInterval('delay');
    enableButton();
  }
}

无CPU消耗,无内存浪费。