-2

I'm looking for a javascript function that executes when the user leaves the page, similar to the onbeforeunload function, but I don't want the user notified with a dialog box

jaydoggy
  • 105
  • 2
  • 2
    Try the `onunload` event. P.S. I think you meant `onbeforeunload`. – gen_Eric Sep 12 '14 at 20:40
  • 3
    Then don’t return a message? – Ry- Sep 12 '14 at 20:42
  • 1
    Why do you want to do this? Are you wanting to send data to the server? If so, be wary of doing this as it's [not reliable](http://stackoverflow.com/questions/25039281/why-is-ajax-call-in-window-unonload-never-called). – David Sherret Sep 12 '14 at 21:07

2 Answers2

0

This performs an action but doesn't show a dialog box.

        window.onbeforeunload = function(){

            console.log('something');
        }
trvrm
  • 784
  • 5
  • 17
0

As David wrote, sending data to the server doesn't reliably work. However, you can attach an event handler to all links, prevent the default action, wait for the server response and then trigger the user's indented navigation. This is how Piwik and other statistics tools collect information.

For instance:

<script>
$('a').click(function() {
  var my_href = $(this).attr('href');
  $.ajax({url: 'http://some-url-here', success:function() {        
    location.href=my_href; // navigate now
  }});
  return false; // stop default navigation action
});
</script>

This is of course not triggered when the user just closes the tab, fills a form, types a new address etc.

Gogowitsch
  • 1,181
  • 1
  • 11
  • 32