Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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.

like image 576
lvil Avatar asked Jan 03 '12 11:01

lvil


2 Answers

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.

like image 161
beeglebug Avatar answered Sep 19 '22 04:09

beeglebug


I had the same problem and it took a while to understand and resolve, sharing the case details:

There was a custom JS within our template that manipulated the menu. It caused the unload to fire twice, only when clicking on the menu links, not on other links, and only in IE/EDGE.

We eventually stopped the propagation on these links and the problem was resolved.

$('.SELECTOR a[href^="http://"]').on('click', function(e){
    e.stopPropagation();
});

It's a specific bug in your application, therefore you won't find too much information on google.

like image 27
AlonMichaeli Avatar answered Sep 21 '22 04:09

AlonMichaeli