Capturing [removed]

前端 未结 7 1302
逝去的感伤
逝去的感伤 2020-11-28 08:58

I have a form where the input fields are saved onChange. In Firefox (5) this works even when the window is closed, but for Chrome and IE it doesn\'t and I need

7条回答
  •  再見小時候
    2020-11-28 09:40

    There seems to be a lot of misinformation about how to use this event going around (even in upvoted answers on this page).

    The onbeforeunload event API is supplied by the browser for a specific purpose: The only thing you can do that's worth doing in this method is to return a string which the browser will then prompt to the user to indicate to them that action should be taken before they navigate away from the page. You CANNOT prevent them from navigating away from a page (imagine what a nightmare that would be for the end user).

    Because browsers use a confirm prompt to show the user the string you returned from your event listener, you can't do anything else in the method either (like perform an ajax request).

    In an application I wrote, I want to prompt the user to let them know they have unsaved changes before they leave the page. The browser prompts them with the message and, after that, it's out of my hands, the user can choose to stay or leave, but you no longer have control of the application at that point.

    An example of how I use it (pseudo code):

    onbeforeunload = function() {
    
      if(Application.hasUnsavedChanges()) {
        return 'You have unsaved changes. Please save them before leaving this page';
      }
    
    
    };
    

    If (and only if) the application has unsaved changes, then the browser prompts the user to either ignore my message (and leave the page anyway) or to not leave the page. If they choose to leave the page anyway, too bad, there's nothing you can do (nor should be able to do) about it.

提交回复
热议问题