卸载确认后如何清理?

时间:2015-02-27 23:49:01

标签: javascript events

网页在向用户显示时可能与服务器具有开放连接。如果在用户从页面导航时可以关闭此连接,那将是很好的。但是,如果用户也应该获得确认窗口,这似乎是不可能的。因为用户点击“离开页面”后页面立即关闭。因此,在用户确认离开后无法关闭资源。

这里有一个简单的结果示例(不起作用):

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 );

如您所见,目前无法调用 afterUnloadConfirmation()方法来正确关闭WebSocket连接。

用户确认离开后有没有办法清理资源?

0 个答案:

没有答案