1. 程式人生 > >用js判斷頁面重新整理或關閉的方法(onbeforeunload與onunload事件)

用js判斷頁面重新整理或關閉的方法(onbeforeunload與onunload事件)

Onunload,onbeforeunload都是在重新整理或關閉時呼叫,可以在<script>指令碼中通過window.onunload來指定或者在<body>裡指定。區別在於onbeforeunload在onunload之前執行,它還可以阻止onunload的執行。 
  Onbeforeunload也是在頁面重新整理或關閉時呼叫,Onbeforeunload是正要去伺服器讀取新的頁面時呼叫,此時還沒開始讀取;而onunload則已經從伺服器上讀到了需要載入的新的頁面,在即將替換掉當前頁面時呼叫。Onunload是無法阻止頁面的更新和關閉的。而 Onbeforeunload 可以做到。 


頁面載入時只執行onload 
頁面關閉時先執行onbeforeunload,最後onunload 
頁面重新整理時先執行onbeforeunload,然後onunload,最後onload。 

1、onbeforeunload事件:
  說明:目前三大主流瀏覽器中firefox和IE都支援onbeforeunload事件,opera尚未支援。 
  用法: 
   ·object.onbeforeunload = handler 
   ·<element onbeforeunload = “handler” … ></element> 
  描述: 
   事件觸發的時候彈出一個有確定和取消的對話方塊,確定則離開頁面,取消則繼續待在本頁。handler可以設一個返回值作為該對話方塊的顯示文字。 


  觸發於: 
   ·關閉瀏覽器視窗 
   ·通過位址列或收藏夾前往其他頁面的時候 
   ·點選返回,前進,重新整理,主頁其中一個的時候 
   ·點選 一個前往其他頁面的url連線的時候 
   ·呼叫以下任意一個事件的時候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit. 
   ·當用window open開啟一個頁面,並把本頁的window的名字傳給要開啟的頁面的時候。 

   ·重新賦予location.href的值的時候。 
   ·通過input type=”submit”按鈕提交一個具有指定action的表單的時候。 
  可以用在以下元素: 
   ·BODY, FRAMESET, window 
  平臺支援: 
   IE4+/Win, Mozilla 1.7a+, Netscape 7.2+, Firefox0.9+ 
  示例: 
複製程式碼程式碼如下:
   <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> 

2、onunload事件
  用法: 
   ·object.onbeforeunload = handler 
   ·<element onbeforeunload = "handler"></element> 

  描述: 
   當用戶關閉一個頁面時觸發 onunload 事件。 

  觸發於: 
   ·關閉瀏覽器視窗 
   ·通過位址列或收藏夾前往其他頁面的時候 
   ·點選返回,前進,重新整理,主頁其中一個的時候 
   ·點選 一個前往其他頁面的url連線的時候 
   ·呼叫以下任意一個事件的時候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit. 
   ·當用window open開啟一個頁面,並把本頁的window的名字傳給要開啟的頁面的時候。 
   ·重新賦予location.href的值的時候。 
   ·通過input type=”submit”按鈕提交一個具有指定action的表單的時候。 
  示例: 
複製程式碼程式碼如下:
   <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> 

一個判斷頁面是否真的關閉和重新整理的好方法: 
複製程式碼程式碼如下:
window.onbeforeunload=function (){ 
alert("===onbeforeunload==="); 
if(event.clientX>document.body.clientWidth && event.clientY < 0 || event.altKey){ 
alert("你關閉了瀏覽器"); 
}else{ 
alert("你正在重新整理頁面"); 



這段程式碼就是判斷觸發onbeforeunload事件時,滑鼠是否點選了關閉按鈕,或者按了ALT+F4來關閉網頁,如果是,則認為系統是關閉網頁,否則在認為系統是重新整理網頁。