簡體   English   中英

用戶離開頁面時如何刪除 session?

[英]How to delete session when user leaves page?

我有一個只有一頁的小型聊天網站。 當用戶登錄時,我將所有數據保存在 session 中。當用戶通過注銷按鈕注銷時,Session 被刪除。 但是,如果用戶關閉頁面並在 5 分鍾后返回,他仍然處於登錄狀態,因此 session 仍然處於活動狀態,我不希望這樣。

現代瀏覽器中有一個信標請求,當TAB / Z0F4137ED1502B5045D6083AAA258B5C42Z將關閉並保證其交付(不會取消)時,會發送請求。

在它的幫助下,您可以發送終止 session 的請求。

您可以在此處閱讀更多信息: https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API/Using_the_Beacon_API

window.onunload = function analytics(event) {
  if (!navigator.sendBeacon) return;

  var url = "https://example.com/analytics";
  // Create the data to send
  var data = "state=" + event.type + "&location=" + location.href;

  // Send the beacon
  var status = navigator.sendBeacon(url, data);

  // Log the data and result
  console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status);
};

一個通常的實現 - 每 N 秒發送一個 ping 請求,並將最后一個請求的時間戳存儲在 session 中。 當 session 開始檢查其時間戳與當前時間戳並取消設置當前會話的變量時,如果它的差異超過 2-3 個時間幀。

以下是您的問題的一些答案:

關閉瀏覽器選項卡時取消設置 Session

PHP - Session 關閉瀏覽器后銷毀

But you can send frequent ajax requests to the server to keep the session and if within 10 second there was no ajax request, you unset session

setInterval(() => {
    // ajax requset
}, 1000)

暫無
暫無

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

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