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 t
In the case you need to do some asynchronous code (like sending a message to the server that the user is not focused on your page right now), the event beforeunload
will not give time to the async code to run. In the case of async I found that the visibilitychange
and mouseleave
events are the best options. These events fire when the user change tab, or hiding the browser, or taking the courser out of the window scope.
document.addEventListener('mouseleave', e=>{
//do some async code
})
document.addEventListener('visibilitychange', e=>{
if (document.visibilityState === 'visible') {
//report that user is in focus
} else {
//report that user is out of focus
}
})