Javascript - Thoughts on how to detect the close button

Purpose: try to detect if the user is leaving the site (either by closing the browser, navigating to another site).

There are multiple ways for the user to leave a site:

  • Clicking on the browser's close button
  • Entering a new URL in the browser's address bar
  • Using the browser's buttons (back, forward, home, search box)
  • Clicking on bookmarked links
  • Closing the browser using hotkey

The below technique is not perfect.

Can we have / detect onmouseout on the <body>? If the window unload while the document does not have the mouse, it must be a control button (either the close button, the refresh, forward, back button, etc), or the user enter the address bar.

screenTop > 9999

Can we detect the coordinate of the mouse by comparing the document against the window. We can figure out the space occupied by chrome using offsetHeight

What happen if people do not click on the close button, but use a shortcut key or menu item to close the browser.

window.event.clientX < 0 && window.event.clientY < 0

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License