簡體   English   中英

如何檢測用戶何時離開網站?

[英]How to detect when a user leaves the site?

我正在閱讀這個問題: 嘗試檢測瀏覽器關閉事件

但它不夠全面,或者至少我不確定,我需要檢測用戶何時離開網站,這可能是:

  • 互聯網死了
  • PC 關閉(例如停電)
  • 用戶關閉瀏覽器
  • 用戶關閉運行網站的瀏覽器選項卡

我相信還有更多的案例。

這可能需要由服務器管理,而不是一些在極端情況下不會觸發的 javascript 事件。

在這種情況下可以使用什么想法?

您可以使用 socket.io 並偵聽套接字何時丟失,或者您可以讓您的站點向服務器發送心跳,如果 X 毫秒過去了而沒有脈沖,您可以假設用戶因您列出的任何原因離開.

我正在使用 Java Script 來檢測離開的事件並向我的服務器發送 ajax 請求,以便我可以存儲用戶離開頁面的信息。 第二部分是檢測用戶在我的頁面中的時間,每隔3秒我也會向我的數據庫發送一個ajax請求來保存用戶在頁面中的時間。

<script>



window.onbeforeunload = function(){//If user left the page
    user_left_page();
};
function user_left_page(){//USER LEFT THE PAGE send data to php to store into my database
    var action = "left_page";
    $.ajax({
        url:"includes/track-page-time.inc.php",
        method:"POST",
        data:{ action: action},
        success: function(data){
        },
    });
}
//This one below is to store the time the user is spending in your page. I am using both
// in my code, basically I keep storing the data every 3 seconds to know the time
setInterval(function () {
    update_user_activity();
}, 3000);//Interval time to send the info to the database

function update_user_activity(){//IS USER IN THE PAGE?
    var action = "update_time";
    $.ajax({
        url:"includes/track-page-time.inc.php",
        method:"POST",
        data:{ action: action},
        success: function(data){
        },
    });
}



</script>

您可以將 window.onbeforeunload 用於最后兩種情況,即檢測瀏覽器關閉或選項卡關閉事件。 對於前兩個事件是斷電或者連接問題,只有不斷ping或者像AlienWebguy所說的心跳機制才能實現。

另一種簡單的方法可以跟蹤 IP/會話 ID 並保存在數據庫中,您可以使用 ajax 調用每隔 5 或 10 分鍾更新數據庫中的時間。

如果用戶沒有進行任何活動並且時間不會更新,如果 db 中的時間小於time() - $intervals ,那么您可以假設用戶已經離開,失去連接等。

 window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }

參考站點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM