在目前視窗關閉前,偵測目前視窗是否關閉
<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>