skip to Main Content

I have a small chat website with only one page. I save all the data in session when user logs in. Session is deleted when user logs out through a logout button. But if user closes the page and comes back in like 5 minutes, he is still logged in, thus session is still active and I don’t want that.

2

Answers


  1. Here are some answers for your problem:

    Unset Session When browser tab is closed

    PHP – Session destroy after closing browser

    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)
    
    Login or Signup to reply.
  2. There’s a beacon request in modern browsers that sends a request when a tab / windows is gonna be closed and guarantees its delivery (it won’t be cancelled).

    With its help you can send a request to terminate a session.

    More info you can read here: 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);
    };
    

    A usual implementation – to send a ping request every N seconds and store the timestamp of the last request in the session.
    When session starts to check its timestamp with current one and unset current session’s variables if it differs more than 2-3 timeframes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search