How can I ask a web user for confirmation if he really wants to leave the page?
How can I ask the user Are you sure you want to leave the page?
Like for example if you 开发者_如何学Pythonclick the back button while asking a question on Stackoverflow?
The easiest way to do this is to bind an event handler to the "unload" JavaScript event. jQuery makes this very easy to do with its .unload() event handler. In the method you bind you can check to see if any the page's form fields have text input. Assuming they do pop an alert notifying the user they'll lose any unsaved data if they navigate from the page.
This method will fire an alert whenever the user navigates away from the page for any reason.
$(window).bind('beforeunload', function() {
alert('Handler for .beforeunload() called.');
});
That's obviously not very user friendly but a couple of quick modifications can make it workable to your question.
精彩评论