Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect window closed

I'm creating a chat client which uses a database to check the status of a session 0-waiting, 1-running, 2-closed.

I have a close button which will change the status to 2 but I was wondering, how do I detect if the browser is closed just by pressing x?

The main reason for this is I don't want the session showing up as running when one of the participants has closed their browser.

like image 633
THEK Avatar asked Mar 30 '26 22:03

THEK


1 Answers

You could listen for the onbeforeunload-event with JavaScript, which is fired when the browser window is closed.

As you tagged the question with jquery, you can use .unload():

$(window).unload(function() {
  // Do some ajax-request to kill the session
});

Without jQuery it would be:

window.onbeforeunload = function() {
   // Do some ajax-request to kill the session
};
like image 53
Christofer Eliasson Avatar answered Apr 02 '26 03:04

Christofer Eliasson