How can I detect when the browser’s tab or window is being closing in Vaadin?
My situation is that I have a background thread that starts and stops when a user enters or exits a view in the browser. The thread is started or stopped based off of navigator’s change listener’s beforeViewChange and afterViewChange events. When I switch between views, within the application, this all works fine.
My problem is if the view with the background thread is active and the user closes the browser tab or window, I don’t know how to detect this closure so I can stop my background thread. Currently if I close the browser, the backend thread keeps running on the server.
You may add a DetachListener to your UI. A DetachEvent is sent, when the server missed three consecutive heartbeats signals from the client.
addDetachListener(new DetachListener() {
@Override
public void detach(DetachEvent event) {
... closeBackgroundThread()
}
});
See https://vaadin.com/docs/-/part/framework/application/application-lifecycle.html for Details about UI Expiration.
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