Best way to detect when a user leaves a web page?

前端 未结 8 2165
太阳男子
太阳男子 2020-11-22 01:57

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

8条回答
  •  心在旅途
    2020-11-22 02:15

    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
        }  
    })

提交回复
热议问题