Sunday, May 20, 2012

Best way to detect when user leaves a web page


What is the best way to detect if a user leaves a web page?



The onunload JavaScript event doesn't work every time (the HTTP request takes longer than the time required to terminate the browser).



Creating will probably be blocked by current browsers.


Source: Tips4all

4 comments:

  1. Try the onbeforeunload event: It is fired just before the page is unloaded

    It also allows you to ask back if the user really wants to leave.

    see this demo

    alternatively, you can send out an ajax request when he leaves.

    ReplyDelete
  2. One (slightly hacky) way to do it is replace and links that lead away from your site with an AJAX call to the server-side, indicating the user is leaving, then use that same javascript block to take the user to the external site they've requested.

    Of course this won't work if the user simply closes the browser window or types in a new URL.

    To get around that, you'd potentially need to use Javascript's setTimeout() on the page, making an AJAX call every few seconds (depending on how quickly you want to know if the user has left).

    ReplyDelete
  3. In Silverlight there is a event in App.xaml.cs Exit. The default handler for it Application_Exit. It fires when you leave the application.

    ReplyDelete
  4. Mozilla Developer Network has a nice description and example of onbeforeunload.

    ReplyDelete