How can I ask a web user for confirmation if he really wants to leave the page?

前端 未结 1 807
执笔经年
执笔经年 2020-12-06 13:05

How can I ask the user Are you sure you want to leave the page?

Like for example if you click the back button while asking a question on Stackoverflow?

相关标签:
1条回答
  • 2020-12-06 13:52

    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.

    0 讨论(0)
提交回复
热议问题