用js判斷頁面刷新或關閉的方法(onbeforeunload與onunload事件)html
Onunload,onbeforeunload都是在刷新或關閉時調用,能夠在<script>腳本中經過window.onunload來指定或者在<body>裏指定Onunload,onbeforeunload都是在刷新或關閉時調用,能夠在<script>腳本中經過window.onunload來指定或者在<body>裏指定。區別在於onbeforeunload在onunload以前執行,它還能夠阻止onunload的執行。 Onbeforeunload也是在頁面刷新或關閉時調用,Onbeforeunload是正要去服務器讀取新的頁面時調用,此時還沒開始讀取;而onunload則已經從服務器上讀到了須要加載的新的頁面,在即將替換掉當前頁面時調用。Onunload是沒法阻止頁面的更新和關閉的。而 Onbeforeunload 能夠作到。瀏覽器
頁面加載時只執行onload 頁面關閉時先執行onbeforeunload,最後onunload 頁面刷新時先執行onbeforeunload,而後onunload,最後onload。服務器
一、onbeforeunload事件: 說明:目前三大主流瀏覽器中firefox和IE都支持onbeforeunload事件,opera還沒有支持。 用法:測試
·object.onbeforeunload = handler ·<element onbeforeunload = 「handler」 … ></element>
描述: 事件觸發的時候彈出一個有肯定和取消的對話框,肯定則離開頁面,取消則繼續待在本頁。handler能夠設一個返回值做爲該對話框的顯示文本。ui
觸發於:url
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>onbeforeunload測試</title> <script> function checkLeave(){ event.returnValue="肯定離開當前頁面嗎?"; } </script> </head> <body onbeforeunload="checkLeave()"> </body> </html>
二、onunload事件 用法:firefox
·object.onbeforeunload = handler ·<element onbeforeunload = "handler"></element>
描述: 當用戶關閉一個頁面時觸發 onunload 事件。code
觸發於:orm
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>onunload測試</title> <script> function checkLeave(){ alert("歡迎下次再來!"); } </script> </head> <body onunload="checkLeave()"> </body> </html>
一個判斷頁面是否真的關閉和刷新的好方法:xml
window.onbeforeunload=function (){ alert("===onbeforeunload==="); if(event.clientX>document.body.clientWidth && event.clientY < 0 || event.altKey){ alert("你關閉了瀏覽器"); }else{ alert("你正在刷新頁面"); } }
這段代碼就是判斷觸發onbeforeunload事件時,鼠標是否點擊了關閉按鈕,或者按了ALT+F4來關閉網頁,若是是,則認爲系統是關閉網頁,不然在認爲系統是刷新網頁。