2008-09-26 116 views
4

是否有任何方式知道用戶是否在Web瀏覽器中關閉了一個選項卡?特別是IE7,還有FireFox和其他。如果包含我們網站的當前標籤關閉,我希望能夠從我們的asp代碼處理這種情況。在Web瀏覽器中捕捉選項卡關閉事件?

回答

2

附加「onbeforeunload」事件。它可以在瀏覽器/選項卡關閉之前執行代碼。

1

是否document.unload不這樣做,如果你?

+0

document.unload是客戶端,所以你不得不走了一步,以便能夠處理它的服務器端(在你的ASP代碼)和也許會從文檔卸載事件處理程序中觸發一個AJAX請求? – kristian 2008-09-26 09:14:15

+0

異步調用是否工作?我的意思是...該標籤正在被殺死,當然最好是同步並以某種方式鎖定它。 – 2008-09-26 09:15:44

0

如果您需要知道服務器端的頁面何時關閉,最好的辦法是定期從頁面ping服務器(例如通過XMLHttpRequest)。當ping停止時,頁面關閉。如果瀏覽器崩潰,被終止或計算機被關閉,這也可以工作。

0

正如Eran Galperin建議的那樣,使用onbeforeunload。特別是,返回一個字符串,該字符串將包含在一個確認對話框中,該對話框允許用戶選擇是否離開該頁面。每個瀏覽器都會在返回的字符串前後包含一些文本,因此您應該在不同的瀏覽器中測試以查看用戶將會看到的內容。

6

onbeforeunload也被稱爲對下列事項 -

* Close the current browser window. 
* Navigate to another location by entering a new address or selecting a Favorite. 
* Click the Back, Forward, Refresh, or Home button. 
* Click an anchor that refers the browser to another Web page. 
* Invoke the anchor.click method. 
* Invoke the document.write method. 
* Invoke the document.open method. 
* Invoke the document.close method. 
* Invoke the window.close method. 
* Invoke the window.open method, providing the possible value _self for the window name. 
* Invoke the window.navigate or NavigateAndFind method. 
* Invoke the location.replace method. 
* Invoke the location.reload method. 
* Specify a new value for the location.href property. 
* Submit a form to the address specified in the ACTION attribute via the INPUT type=submit control, or invoke the form.submit method. 

所以,如果你想,如果他們關閉選項卡或瀏覽器窗口註銷用戶,你最終會登陸出來每次他們點擊鏈接或提交頁面。

0

桑托斯是對的,這個事件將被觸發許多更多的行動,而不僅僅是點擊你的標籤頁/瀏覽器的關閉按鈕。我已經創建了一些小工具來防止onbeforeunload動作被添加到文檔準備好的以下函數觸發。

 $(function() {  
     window.onbeforeunload = OnBeforeUnload; 
      $(window).data('beforeunload', window.onbeforeunload); 
      $('body').delegate('a', 'hover', function (event) { 
       if (event.type === 'mouseenter' || event.type === "mouseover") 
        window.onbeforeunload = null; 
       else 
        window.onbeforeunload = $(window).data('beforeunload'); 
      }); 
     }); 

此外,您觸發任何由桑托斯提到的事件之前,你需要運行這一行:

window.onbeforeunload = null; 

如果你不希望事件被觸發。

而這裏的最後一段代碼:

function OnBeforeUnload(oEvent) { 
      // return a string to show the warning message (not every browser will use this string in the dialog) 
      // or run the code you need when the user closes your page 
     return "Are you sure you want to close this window?";  
    }