Detect browser or tab close event using javascript and perform operation

Hi,

I want to update flag in database when user logout.

I am doing it when user logout using logout button.

I want to same when user close browser or tab.

How to identify event of close browser or tab using jquery and javascript.

Any idea?

-Thanks

Hi,

Your best bet would be to use window.onbeforeunload, an event which is fired when the window is about to unload its resources.

window.onbeforeunload = function(){
  // Ajax request to update db here
}

However, this has a couple of drawbacks: the event will fire if the user refreshes the page and the AJAX request is not guaranteed to ever reach the server.

A more reliable way to do this might be to have a relatively short session timeout on the server side (e.g. 1 minute) and introduce an AJAX based heartbeat on the client side (e.g. every 30 seconds) to keep the session alive.

You might find these links useful:

http://ajaxpatterns.org/Heartbeat

1 Like

Many thanks for Pullo,

You are right. I solve this problem using session,cron jobs and database flags.

-Thanks