How can I handle the close event of a browser to trigger a logout?
Deleting Session Data Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with a particular key. Delete the whole session − You can call public void invalidate() method to discard an entire session.
"Closing" a session happens by invalidate() method. It destroys the entire session and unbinds all of the attributes. Any next HTTP request will result in a fresh new session.
Jakarta EE/Java JEE 8 Web Development(Servlet, JSP and JDBC) The session object is used to track a client session between client requests. JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across. a one-page request or. visit to a website or.
I've searched for a consistent solution to this problem some time ago, and my decision was to handle the situation without believing the browser or the user.
You can't for sure know if a user is leaving your page and when, and even if you use 'onunload', you may not get the event before the browser closes or leaves your page. And browser crashes won't give you any kind of signal, so believing you know the user is still viewing you page and may take any further action is flawed.
The best you can do about logging out an user is put a fitting session timeout, and if you need further control, you may try adding AJAX calls on critical pages with 'I'm alive' signals, and then logging out users that are not responding anymore (that would require AJAX/JS enabled browser and may exclude potential users).
You're looking for the onunload:
window.onunload = function() {
// check the window is closed (see point 1 below)
// do log out
}
There are 2 problems with this:
I recommend using a different approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With