Js popup when leaving page but not when submitting form

梦想与她 提交于 2019-12-20 07:31:53

问题


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

<script type="text/javascript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {

    return "Si vous quittez ou actualisez la page, vous perdrez votre tutoriel";
  }
</script>

However, this is on a page with a form. When the user submits the form, the popup appears which doesn't make sense. How can I modify this code so the popup appears only when the user leaves the page in every way possible (close the tab, clicks on site logo, refresh the page) but not when submitting the form ?


回答1:


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.



来源:https://stackoverflow.com/questions/32667042/js-popup-when-leaving-page-but-not-when-submitting-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!