2012-01-26 228 views
0

我有一个网页,打开另一个窗口。检查浏览器窗口关闭

当单击按钮并打开新页面时,我禁用该按钮(因为只需要打开一个页面,单击此按钮)。 我使用window.open()而不是windows.showModalDialog(),因为用户应该在两个页面上工作。

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

我”试图与成才是这样的:

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

但使用while循环减慢太多的浏览器,所以它实际上不可能在第一页上工作...

是否有更好的解决我的问题?

回答

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

完美!非常感谢你! :) – davioooh

+0

谈论睡眠......这也可能有所帮助:http://www.phpied.com/sleep-in-javascript/ – davioooh

+0

不,这会遭遇同样的问题:循环不断循环,直到条件成立满足。 CPU使用率将保持高位,并且您的浏览器将“挂起”。阅读文章评论,有些人也提到它。 – Konerak

0

我想你可以将事件unloadbeforeunload事件绑定:

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

但是,如果用户在窗口中加载不同的页面,这将也被称为,所以你仍然想在事件处理程序中检查win.closed

0

如果你通过JavaScript用户将刷新页面处理1,本会fail.So在第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 
    } 
按钮的按钮属性
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和内存没有浪费。