How to call a function before leaving page with Javascript

前端 未结 8 544
遇见更好的自我
遇见更好的自我 2020-12-05 13:50

I would like to execute a function before leaving page without showing a confirmation popup with Javascript only. I\'ve tried with the code below but it did

相关标签:
8条回答
  • 2020-12-05 14:10

    What you're doing there is definitely not going to do it. Comparing window.onbeforeunload to true at some arbitrary time doesn't even make sense.

    What's with the commented out code at the end? If anything, you need to assign a function to onbeforeunload:

    var result = 'test';
    
    window.onbeforeunload = function() {
      result = 'test1';
      alertmess();
    }
    
    function alertmess() {
      alert(result);
    }
    

    However, the above only appears to work in IE. Please see @Bulk's comment and @Brandon Gano's answer.

    0 讨论(0)
  • 2020-12-05 14:12

    This is an example of how you could handle the navigate away. Notice how a div appears a little before the navigation occurs.

    window.onbeforeunload = function () 
    {
       $("#oi").append($('<div>This is the child DIV</div>'));
     
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="theMainDiv">
      The Main Div will receive another div before leaving the page
    </div>
    
    <button onclick="window.location.href='pageAway'">Navigate Away</button>

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