Implementing “this page is asking you to confirm that you want to leave”

前端 未结 2 1838
长情又很酷
长情又很酷 2021-02-19 19:33

This is a warning that Firefox raises when I want to leave certain pages. Based on the pages I\'ve seen this on and that this warning appears when I try to close the page after

2条回答
  •  走了就别回头了
    2021-02-19 20:07

    You basically implement a handler for beforeunload event. This allows you to warn your users that they have unsaved data.

    Pseudo Code:

      window.onbeforeunload = function warnUsers()
      {
        if (needToConfirm)
        {
          // check to see if any changes to the data entry fields have been made
          if(changesPresent) {
                return message to display
          }
          else {
          // no changes - return nothing      
          }
        }
      }
    

    Here's a very good article that discusses this in depth: http://www.4guysfromrolla.com/webtech/100604-1.shtml

    Note: There is onunload event also but that fires after the page has unloaded, hence is too late to take any reliable action. You should never put any critical code in onunload as that is never guranteed to execute.

提交回复
热议问题