2013-05-14 137 views
11

我目前正在檢測我的網站用戶是否關閉窗口/選項卡或更改網址。關於窗口關閉事件的javascript

我使用的follwoing代碼,它完美的作品:

var validNavigation = false; 

function endSession() { 
    // Browser or broswer tab is closed 
    // Do sth here ... 
    alert("bye"); 

} 

function wireUpEvents() { 

    window.onbeforeunload = function() { 
     if (!validNavigation) { 
     endSession(); 
     } 
    } 

    // Attach the event keypress to exclude the F5 refresh 
    $(document).bind('keypress', function(e) { 
    if (e.keyCode == 116){ 
     validNavigation = true; 
    } 
    }); 

    // Attach the event click for all links in the page 
    $("a").bind("click", function() { 
    validNavigation = true; 
    }); 

    // Attach the event submit for all forms in the page 
    $("form").bind("submit", function() { 
    validNavigation = true; 
    }); 

    // Attach the event click for all inputs in the page 
    $("input[type=submit]").bind("click", function() { 
    validNavigation = true; 
    }); 

} 


$(document).ready(function() { 
    wireUpEvents(); 
}); 

我的問題是我想的事件從警報更改爲疊加。我已經安裝了一個隱藏的div覆蓋在上面的代碼替換爲警報:

$('.overlay').css('display','block'); 

現在這不再起作用,因爲是div內沒有獲得用戶停留在頁面上。 (用戶不必點擊警報中的按鈕)

關於如何解決這個問題的任何建議?

乾杯,丹

+0

你爲什麼不乾脆用'window.onbeforeunload'?我知道這不是一個花哨的'div',但它絕對是用於這些類型的東西。 – Powerslave 2013-05-14 10:40:09

+0

window.onbeforeunload是一個選項,但現在我需要一個花哨的div,需要樣式。 – danyo 2013-05-14 10:42:19

+0

複製到http://stackoverflow.com/questions/276660/how-can-i-override-the-onbeforeunload-dialog-and-replace-it-with-my-own/276739 – 2013-05-14 11:38:45

回答

8

窗口關閉事件被觸發的最後事件。因此沒有其他事件在它之後被解僱。

您可以在jquery中使用beforeunload事件來在屏幕上顯示疊加層。

以下鏈接可以幫助:link

+0

您發佈的鏈接是*非常*有幫助。謝謝! – Ethereal 2013-08-29 19:11:25