Detection window is closed

I am creating a chat client that uses a database to check the status of a 0-wait, 1-working, 2-closed session.

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

The main reason for this is that I do not want the session to appear as working when one of the participants closed his browser.

+1
javascript jquery php window
source share
3 answers

use the unload and onbeforeunload :

 window.onunload = window.onbeforeunload = function (){...}; 

It is better to register for both events to make sure that the callback will work.

+3
source share

You can listen to onbeforeunload-event using JavaScript, which runs when the browser window closes.

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

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

Without jQuery, this would be:

 window.onbeforeunload = function() { // Do some ajax-request to kill the session }; 
+4
source share

You can use the beforeunload event because the unload event is deprecated in jQuery version 1.8, and the beforeunload event is fired whenever a user leaves your page.

 $(window).bind("beforeunload", function() { return confirm("Do you really want to close?"); }) 
+1
source share

All Articles