Stop page from unloading within the beforeunload event handler

前端 未结 3 1161
故里飘歌
故里飘歌 2020-12-11 10:02

Before user navigates the page code checks if he edited some of the form fields. If he did, I display a modal window with Yes and No buttons. If he

3条回答
  •  攒了一身酷
    2020-12-11 10:18

    This is possible, but only if the user clicks a hyperlink within the page. If the user uses the browser to navigate away from the page, they will get the default browser dialog, which doesn't have an option to save.

    Dirty Forms automatically attaches (and removes the handler) to the beforeunload event, so your attempt to create another event handler will most certainly fail. You should never do this when using Dirty Forms.

    You didn't mention which modal dialog framework you wanted to use, so I will just show an example using jQuery UI dialog. Integrating other dialog frameworks is similar. To do so, you might want to check out the source code of the existing pre-built dialogs.

    Also, your use case is a bit short-sided. What if the user wants to navigate away and ignore the changes? I have added an example that includes an additional option to do just that.

    
    
        
    
    
    
        
        
    
        Change one of the fields below, then click "Go to Google" to try to navigate away.
    
        
    First name:
    Last name:
    Go to Google

    The example uses custom event binding to attach to the onRefireClick event handler, which is fired when choice.proceed = true, but not when it is false.

提交回复
热议问题