Detect whether the current window is closed before the current window is closed
<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>
In IE9, if the document is refreshed, both unloadform and onbeforeunload will be executed. If the page is closed, only the onbeforeunload event will be executed
It is worth noting that onunload will not run when the page is closed. It is estimated that this function is a built-in event of the browser and cannot be redefined
In Chrome, if you refresh the document, both unloadform and onbeforeunload will be executed. If you close the page, only onbeforeunload will be executed. It is worth noting that the commented line will never be executed.
If it is a child window opened by window.open, you can use the window.closed property to detect whether it is 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>
Code that automatically closes window.open when the parent window is closed
<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>