Use beforeunload event to warn user

This PR will close #478, #475 and #491.