Sessions DO NOT end when a user closes their browser. There is no communication with the server when a browser is closed so there is no way the server can know to end the session. The same is true when you leave the site for another. Again no communication takes place between your browser and the site you're leaving so the server never knows you've left.

Basically the only solution I know of is to set up a client-side event to call a server-side script to abandon the session when the user leaves.

Anyone knows how to write a javascript to end a session when the browser is being closed?

Dani AI

Generated

Briefly: the browser won't reliably tell the server “I'm gone,” so client-side signals are only best-effort. Combine a short server-side TTL (authoritative) with one of these client techniques to get the behavior you want. This ties to points made by and but adds practical, modern patterns.

Best-effort unload notification (use navigator.sendBeacon with fallbacks)

function notifyAbandon(){
  const url = '/session/abandon';
  if(navigator.sendBeacon){
    navigator.sendBeacon(url);
    return;
  }
  fetch(url, { method: 'POST', keepalive: true, credentials: 'same-origin' })
    .catch(()=> (new Image()).src = url + '?_=' + Date.now());
}
window.addEventListener('unload', notifyAbandon);

Heartbeat / polling (robust for reservations — server extends TTL on each ping)

const HB_MS = 30000; // tune for load vs responsiveness
const hb = setInterval(()=> {
  fetch('/session/ping', { method: 'POST', credentials: 'same-origin' });
}, HB_MS);
window.addEventListener('beforeunload', ()=> clearInterval(hb));

WebSockets (best for real-time apps)

  • Open a WebSocket per client; when the socket disconnects the server gets a reliable callback and can free resources immediately. Use ping/pong and authenticate the socket.

Avoid false positives when users navigate inside your site

  • Set a flag on internal link clicks/forms so unload handlers don’t abandon the session during normal in-site navigation:
let internalNav = false;
document.addEventListener('click', e=>{
  const a = e.target.closest && e.target.closest('a');
  if(a && a.hostname === location.hostname) internalNav = true;
});
window.addEventListener('unload', ()=> {
  if(!internalNav) navigator.sendBeacon('/session/abandon');
});

Cautions and recommendations

  • Treat client notifications as hints only. Always have server-side expiration and a background cleanup job. Protect the abandon endpoint from CSRF (check Origin/Referer or require a short-lived token). For seat reservations, use a short server TTL plus heartbeat so seats are released reliably even when the client cannot notify.

Why do you need this? The session object is killed when they close the browser (i know you store information in there and may be worreid about it). Are you trying to achieve something else too?

There are occassions where you want to know when the client is gone, but not often (chat programs and instant messengers and the like). It depends who needs to know. You can get them to poll to know if they are there. But its an overhead on the network when you have a lot of clients.

There are a number of ways to do it, but if you let me know exactly what you are trying to achieve i can give you the best way to do it, in terms of performance and resources etc.

Like I said, think about it. For your movie app i dont think you would need to go to that extreme. Are you trying to release provisionally booked seats for others? If that is the case then the best way would be on a timer. For a person to book a seat there has to be a time window. You can log each postback time so you know the person is still transacting with you. After a respectable period of inactivity you can assume they are gone. Also you could use the timer principle from another post to prompt the user to continue the transaction or they will be timed out and the seat released (just use the timer as with the other post about disabling the button but this time use an alert to send them a message. ) if they dont respond within a timeframe after that then release the seat.

It saves a lot of polling and call backs when it isnt necessary in your case to consume that bandwidth. I know a call back might not seem much bandwidth but you take your application for a multiplex theatre that is showing the world premiere of LOTR on 5 screens then you suddenly have a few thousand callbacks going on at the same time. Lots of bandwidth then.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.