Detecting a closed browser

Occasionally I want to determine if a browser window has been closed - possibly soon after it happens. At present I set a rapid heartbeat interval (10s) and test if the user interface is still attached, something like:

if ( !someUserInterface.isAttached() ) {  ... do something  }

It works, but there are two drawbacks:

  • it takes 3 heartbeat intervals, ~30 seconds before the UI expires and its absence can be detected,
  • there are a lot of unnecessary heartbeats being generated.

Is there a better way? Perhaps some aspect of the push channel that could be used to more quickly identify an absent browser?

Vaadin 7.1.9, Tomcat 7.0.47, using Push, WEBSOCKET

There’s the “onbeforeunload” event in JavaScript, which I think is Window.ClosingEvent in GWT.

Vaadin 6 used to inform the server about window closing by sending a XHR request, but it was abandoned because it was unreliable, as browser crashes and such would not be detected.

So, if you want to detect window closing in ~99% of cases, you could use that.

Good question. In principle this is possible; the serverside in most cases should be notified immediately when a WebSocket connection is closed by the browser. However, the problem is deciding whether the disconnection occurred due to the client actually going away, or whether it’s just going to reconnect shortly. We could send a going away notification when the browser is closing the page, but that has the regular issues due to unreliability that lead to the removal of Vaadin 6’s close listener support from Vaadin 7.

However, we’ve been thinking about reintroducing close listeners – even if they’re not 100% reliable, they can still be used to optimize the cleanup in most cases - and there’s still the heartbeat as a backup mechanism, unlike in Vaadin 6.