How to control when closing a window

2019-06-11 06:29发布

问题:

I have this code, which alerts the user that the window is about to be closed and the user may loose the data. If the user accpets the window closes, if not, the user stays on the page.

<script language='javascript'>
   ClosingVar =true
   window.onbeforeunload = ExitCheck;
   function ExitCheck() {
      if(ClosingVar == true) { 
         ExitCheck = false;
         return "YOU MAY LOOSE YOUR DATA.";
      }
   } 
</script>

I want to be able to manage the option of the user. If the accept the closing option, then I want to call a function to do something and then close the window.

Does anyone know how to do this?

Thanks a lot.

回答1:

Try this code I made for you, based on this question.

ps: I know the question in reference uses jQuery, but it's not required.

window.onbeforeunload = function () {

    setTimeout(function () {
        setTimeout(function () {

            alert('Welcome back!');
            // this code will run if they choose to stay on the page
            // run your other code here

        }, 100);
    }, 1);

    return 'YOU MAY LOOSE YOUR DATA.';
};


回答2:

You can use the beforeunload event with Jquery.

The following link could help: link