检查浏览器窗口是否关闭
Check browser window closed
我有一个网页,上面有一个打开另一个窗口的按钮。
当点击按钮并打开新页面时,我会禁用该按钮(因为点击按钮只需要打开一个页面)。我使用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
}
}
我想您可以将事件绑定到unload
或beforeunload
事件:
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消耗,无内存浪费。
相关文章:
- 如何检测用户是否在同一会话中打开了多个窗口或选项卡
- 检查iframe内部的窗口是否已关闭
- 是否可以使用Jquery操作窗体的目标窗口
- 是否可以使用javascript获取以em为单位的窗口宽度
- 用javascript从窗口获取文档,同时检查文档是否已加载
- window.open:是否可以通过修改DOM来打开一个新窗口
- 是否可以从弹出窗口触发内容脚本中的行为
- 在Chrome扩展程序中,是否可以截屏并在弹出窗口中显示屏幕
- 是否可以模拟 qUnit 测试的窗口位置对象
- iframe是否可能在没有主窗口帮助的情况下自行调整大小
- 是否可以使用javascript激活windows应用程序窗口
- 是否可以使用JS打开具有所需内容类型的浏览器窗口
- 是否可以在Kendo网格中只显示来自Kendo数据源的某些字段,而在“;添加“;弹出窗口
- 是否可以打开一个新窗口并将iframe嵌入其中
- 确定是否在不使用任何全局变量的情况下加载了窗口
- jQuery:添加和删除<br>标签,这取决于窗口宽度以及标签是否已经存在
- 如何检查窗口是否已滚动到href,然后在javascript/jQuery中执行函数
- 检查窗口是否为弹出窗口的另一种方法
- 如何检测浏览器窗口是否已从另一个浏览器窗口打开
- 我想知道是否可以使用 node.js 在窗口之间发送数据