Javascript 检查浏览器窗口是否关闭
我有一个网页,上面有一个打开另一个窗口的按钮 单击按钮并打开新页面时,我禁用该按钮(因为单击按钮只需打开一个页面)。 我使用Javascript 检查浏览器窗口是否关闭,javascript,javascript-events,Javascript,Javascript Events,我有一个网页,上面有一个打开另一个窗口的按钮 单击按钮并打开新页面时,我禁用该按钮(因为单击按钮只需打开一个页面)。 我使用window.open()而不是windows.showModalDialog(),因为用户应该在这两个页面上工作 当第二页关闭时,我必须重新启用第一页中的按钮 我试过这样的东西: var win = window.open("SecondPage.htm"); // disable button while (!win.closed
window.open()
而不是windows.showModalDialog()
,因为用户应该在这两个页面上工作
当第二页关闭时,我必须重新启用第一页中的按钮
我试过这样的东西:
var win = window.open("SecondPage.htm");
// disable button
while (!win.closed) {
setTimeout('', 2000);
}
// re-enable button
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
}
}
但是使用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
}
}
我想您可以将事件绑定到或事件:
但如果用户在窗口中加载不同的页面,也会调用此函数,因此,您仍然希望在事件处理程序中检查
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()
,否则只要top.window打开,计时器就会闪烁。按如下方式修复代码:
var win = window.open("SecondPage.htm");
// disable button
while (!win.closed) {
setTimeout('', 2000);
}
// re-enable button
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消耗,无内存浪费。完美!非常感谢!:)谈论睡眠。。。这也可能是有帮助的:不,这会遇到同样的问题:循环不断循环,直到满足条件为止。CPU使用率将保持高水平,浏览器将“挂起”。读了这篇文章的评论,有些人也提到了这一点。