JavaScript 捕獲視窗關閉事件
阿新 • • 發佈:2019-02-01
1.用javascript重新定義 window.onbeforeunload() 事件 在javascript裡定義一個函式即可 function window.onbeforeunload() { alert("關閉視窗")} alert()事件將會在關閉視窗前執行,你也可以使用者決定是否關閉視窗 function window.onbeforeunload() { if (event.clientX>document.body.clientWidth && event.clientY<0 ||event.altKey) window.event.returnValue="確定要退出本頁嗎?";
2.用onUnload方法在body 標籤里加入onUnload事件 body onUnload="myClose()" 然後在javascript裡定義myClose()方法 但是onUnload方法是在關閉視窗之後執行,不是在關閉視窗之前執行,如果你想在關閉視窗之前做判斷,請用第一種方法
以上兩個方法要能夠成功關閉視窗,則該視窗必須是獨立的新視窗;如果是基於父視窗,那麼是無法關閉的。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>匯出資料</title> <script type="text/javascript"> if(top.location != self.location ) { top.location = self.location; } var time = 5; //時間,秒 function Redirect() { //window.location = "http://www.cssue.com/"; window.opener=null; window.open('','_self'); window.close(); } var i = 0; function dis() { if( i > time ) { Redirect(); } document.all.t.innerHTML = "還剩<span style='color:red'>" + (time - i) + "</span>秒,本頁面將自動關閉"; i++; } timer = setInterval('dis()', 1000); //顯示時間 timer = setTimeout('Redirect()', time * 1000); //跳轉 </script> </head> <body > <div style="text-align:center;margin-top:5%"> <h1> <div id="s">Sorry ! 您輸入的資訊在伺服器中無法找到</div> <div id="t"></div> </h1> </div> </body> </html>