control [removed] event

后端 未结 3 798
抹茶落季
抹茶落季 2021-01-25 20:34

From out of curiosity can i Control window.onbeforeunload event like check if the user decided to leave the page or stay in it and can I raise an alert or some function based on

相关标签:
3条回答
  • 2021-01-25 20:45

    You cannot get the result of onbeforeunload. Also, even if you somehow managed to figure out a way to get the result, you wouldn't be able to raise an alert. You could probably run another function.

    The showModalDialog(), alert(), confirm() and prompt() methods are now allowed to do nothing during pagehide, beforeunload and unload events.

    0 讨论(0)
  • 2021-01-25 20:46

    Put a timer of one second. Clear it on unload. Should work, but didn't test it.

    window.addEventListener('beforeunload', function (event) {
    
      var timeId = setTimeout(yourFunctionIfTheUserStays, 1000);
    
      window.addEventListener('unload', function (event) {
        clearTimeout(timeId);
      })
      return 'Are you sure you want to leave this page?';
    });
    
    0 讨论(0)
  • 2021-01-25 20:50

    You can ONLY return a string which will show a dialog confirmation displaying the string you returned (But with additional ok/cancel buttons to confirm the action).

    <script type="text/javascript">
    $(window).bind("beforeunload",function(){
    return 'Are you sure you want to leave this page?';
    });
    </script>
    
    0 讨论(0)
提交回复
热议问题