1

A webpage might have an open connection to a server while it is showing to the user. It would be nice if this connection could be closed when the user navigates from the page. However, this seems impossible if the user should get an confirmation window as well. Because after the user clicks on "Leave Page" the page closes immediately. So there is no way of closing resources after the user confirmed to leave.

Here I have a simple example of the desired result (Doesn't work):

var socket;

// Gets called after the page's DOM is loaded
var loaded = function( event ) {
  socket = new WebSocket( /* */ );
  /* Here the WebSocket is set up */
};

// Gets called when the page is about to unload.
var beforeUnload = function( event ) {
  // Ask for confirmation about closing the session (Firefox)
  event.preventDefault( );
};

// Gets called after the user confirmed unloading the page (This is what should happen)
var afterUnloadConfirmation = function( event ) {
  // Close the WebSocket connection
  socket.close( );
};

// Register the events
document.addEventListener( "DOMContentLoaded", loaded );
window.addEventListener( "beforeunload", beforeUnload );
/*something*/.addEventListener( /*after-beforeunload*/, afterUnloadConfirmation );

As you can see, there is currently no way that the afterUnloadConfirmation() method gets called to properly close the WebSocket connection.

Is there any way to clean up resources after the user has confirmed to leave?

Dennis
  • 323
  • 7
  • 17
  • Aren't all resources associated with a page automatically destroyed when the page is unloaded? – Barmar Feb 27 '15 at 23:54
  • This may be a duplicate post http://stackoverflow.com/questions/4812686/closing-websocket-correctly-html5-javascript – bhspencer Feb 28 '15 at 00:00
  • @Barmar Yes, they are. But I don't think it can be considered "clean" to let the browser clean-up resources. Besides, Firefox actually gives an warning (in the console) about WebSockets that are not closed on exit. – Dennis Feb 28 '15 at 00:46
  • Browsers deliberately limit the kinds of things you can do in handlers for unload-related events, because malicious web sites could (and have) used these methods to prevent you from leaving their sites. – Barmar Feb 28 '15 at 00:51
  • @bhspencer That post doesn't address the same problem. That post is about closing the connection before unload, while mine is about what happens *after* confirming the unload. – Dennis Feb 28 '15 at 00:53
  • @Barmar Does that mean there is no way of cleaning-up resources after the user has confirmed to leave? – Dennis Feb 28 '15 at 01:07
  • 1
    Pretty much. Your best bet is to provide a "Quit" button in the application that does a cleanup. Your `beforeunload` message should warn the user that it's better for them to use this button. – Barmar Feb 28 '15 at 01:10

0 Answers0