Handle window.beforeunload event

Closes #1041