Search code examples
javascriptjqueryajaxdom-eventsonbeforeunload

'onbeforeunload' Fires Twice


I want to send an ajax request when a user leaves a page or closes the window.
Here is my code inside :

<script type="text/javascript">
    function sendajax(){
        $.ajax({
          url: "someurl",
          data: mydata,
          async : false
        });   
    }
</script>
    <script type="text/javascript">
     window.onbeforeunload=function(){sendajax();};
</script>   

When the event occurs the event fires twice.
Why does in happen?
I know I can prevent it by adding a variable var ajaxSent=true; but may be there is a cleaner way to do it?

UPD:
I replaced the sendajax function content with some other code (without sending ajax) and found out that ajax is not the one causing the problem. It still enters the function twice.


Solution

  • Based on the code in your edit and comments, it looks like it could simply be caused by the broken link you are clicking to leave the page.

    Given the following code:

    <script>
        function doSomething() { console.log('onbeforeunload fired'); }
        window.onbeforeunload = doSomething;
    </script>
    <a href="garbage">link A</a>
    <a href="http://google.com">link B</a>
    

    If I click on link A, I get two console log entries, if I click on link B I only get one.

    It looks like it could be a quirk of how the browsers handle their internal "This web page has not been found" pages, causing your page to be refreshed and closed again before showing the message, leaving you with two occurrences of the onbeforeunload event.