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?