检查浏览器窗口是否关

时间:2012-01-26 10:52:12

标签: javascript javascript-events

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

单击该按钮并打开新页面时,我禁用该按钮(因为只需打开一个页面,单击该按钮)。 我使用window.open()而非windows.showModalDialog(),因为用户应该同时使用这两个页面。

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

我尝试过这样的事情:

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

但是使用while循环会减慢浏览器的速度,因此实际上无法在第一页上工作...

我的问题有更好的解决方案吗?

4 个答案:

答案 0 :(得分:0)

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
  }
}

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

如果你通过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
  }

答案 3 :(得分:0)

此Konerak的代码无法解决CPU和内存浪费问题。使用setTimeout时,您也必须使用clearTimeout(),否则只要top.window打开,计时器就会停止。修复这样的代码:

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消耗且没有内存浪费。

相关问题