Making ajax call on navigating away from page

I am working on a site that has multiple links to other sites. What I want is to send an ajax call to report that the user is going away when someone clicks and navigates away from the page. I put an alert on click of the links, which works but for some reason the controller never gets the ping.

Any assistance will be appreciated on how to achieve it.

Can't be done.

When you go to navigate away, there is only one event that can catch that, the onbeforeunload event, and that is quite limited in what it can do.

Not to mention there are other ways of leaving the page without navigating away:

  • Losing network connection
  • Closing the browser.
  • Losing power.

The only thing you can do is to set up a heartbeat kind of thing that pings the server every so many milliseconds and says 'I'm Alive.'

Depending on what you are trying to do, there is usually a better option, however.

You can try to simply set click event handler which will check the href attribute of every link before navigating. If it goes to another website, the handler sends AJAX request and then (after server responding) redirects to the page.

var redirect = '';
$('a').click(function() {
    if (this.href.host != document.location.host) {
        if (redirect) return false; // means redirect is about to start, clicking other links has no effect
        redirect = this.href;
        $.ajax({
            url: '/away', 
            success: function(){document.location.href = redirect;}
        });
    return false;
});

However it can't work properly, if user has opened your page in multiple tabs.

You can try:

$(window).on('beforeunload', function(){
    return "This should create a pop-up";
});

You can achieve it by capturing clicks on all the links on the page (or all the relevant links) and then call ev.preventDefault() on it to prevent the browser from navigating directly to that page.

Instead, you can make an AJAX call to your server and when that call returns, you can set window.location to the URL the user was trying to navigate to.