检测窗口是否关闭,在当前窗口关闭前使用js做到这一点,下面是具体的实现,感兴趣的朋友可以参考下
在当前窗口关闭前,检测当前窗口是否关闭
<pre name="code" class="html"><pre name="code" class="html"><HTML><HEAD>
<script Language="JavaScript">
window.onbeforeunload=function(event){
alert("222"); //这里IE9会执行,CHROME不会执行
// if(event.clientX>document.body.clientWidth && event.clientY<0||event.altKey){ //如果是刷新,则不提示
RETURN "确定关闭窗口?";
// }
}
var aa ;
var intervalVar;
function showClose(){
console.log(" wait and val is :"+aa.closed);
clearInterval(intervalVar);
}
function loadform(){
aa=window.open('foo.html', 'windowName',"width=200,height=200,scrollbars=no");
console.log("check close before op and val is :"+aa.closed); //现在窗口未关闭,结果为false
aa.close();<span style="white-space:pre"> </span> //调用窗口关闭的方法
console.log("not in wait and val is :"+aa.closed); //此时aa.close正在调用过程中,结果为false
intervalVar = setInterval(showClose,100); }; //用循环检测子窗口是否关闭,其实用setTimeout也是可以的,不过值要设得大一些
function unloadform(){ alert("2!"); }
</script>
</HEAD><BODY OnLoad="loadform()" OnUnload="unloadform()">
</BODY></HTML>
在ie9中,如果刷新文档的话,unloadform和onbeforeunload都会执行,如果是关闭页面的话只会执行onbeforeunload事件
值得注意的是,onunload在关闭页面时不会运行,估计此函数为浏览器内置事件,不能重新定义
在chrome中,如果刷新文档的话,unloadform和onbeforeunload都会执行,关闭页面的话,只会执行onbeforeunload,值得注意的是有注释的那一行一直不会执行.
如果是window.open打开的子窗口的话,可以通过window.closed属性检测是否关闭
<HTML><HEAD>
<script Language="JavaScript">
var aa ;
var intervalVar;
function showClose(){
console.log(" wait and val is :"+aa.closed);
clearInterval(intervalVar);
}
function loadform(){
aa=window.open('foo.html', 'windowName',"width=200,height=200,scrollbars=no");
console.log("check close before op and val is :"+aa.closed); //现在窗口未关闭,结果为false
aa.close(); //调用窗口关闭的方法
console.log("not in wait and val is :"+aa.closed); //此时aa.close正在调用过程中,结果为false
intervalVar = setInterval(showClose,100); }; //用循环检测子窗口是否关闭,其实用setTimeout也是可以的,不过值要设得大一些
function unloadform(){ alert("2!"); }
</script>
</HEAD><BODY OnLoad="loadform()" OnUnload="unloadform()"> <a href="test.htm">调用</a>
</BODY></HTML>
父窗口关闭时会自动将window.open关闭的代码
<HTML><HEAD>
<script Language="JavaScript">
var aa ;
var intervalVar;
window.onbeforeunload=function(event){
aa.close();
return "hello";
}
function loadform(){
aa=window.open('test.htm', 'windowName',"width=200,height=200,scrollbars=no");
};
function unloadform(){ alert("2!"); }
</script>
</HEAD><BODY OnLoad="loadform()" OnUnload="unloadform()"> <a href="test.htm">调用</a>
</BODY></HTML> |