在當前窗口關閉前,檢測當前窗口是否關閉
<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>