Js popup when leaving page but not when submitting form

后端 未结 1 750
囚心锁ツ
囚心锁ツ 2021-01-23 13:35

I use this code on my website to display a warning message in a popup when a user trie to leave the page:



        
相关标签:
1条回答
  • 2021-01-23 14:29

    I would suggest capturing the submit event for the form and then either removing the confirmExit function from your onbeforeunload event binding or setting a flag to indicate that the page can be submitted. For example:

    <script type="text/javascript">
    
        // Define flag to determine if the page can be left without confirmation
        var safeToLeave = false;
    
        // Handle user leaving the page
        function handleExit () {
            if (!safeToLeave) {
                return 'Si vous quittez ou actualisez la page, vous perdrez votre tutoriel';
            }
        }
    
        // Handle the user submitting the page form
        function handleSubmission() {
            safeToLeave = true;
        }
    
        // Bind to on evemts
        window.onbeforeunload = handleExit;
        document.getElementById('#my-form').onsubmit = handleSubmission;
    
    </script>
    

    I'd recommend you consider using the addEventListener method for binding events in general, however given your example I've tried to keep my answer consistent.

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