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

前端 未结 8 2381
太阳男子
太阳男子 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

    Thanks to Service Workers, it is possible to implement a solution similar to Adam's purely on the client-side, granted the browser supports it. Just circumvent heartbeat requests:

    // The delay should be longer than the heartbeat by a significant enough amount that there won't be false positives
    const liveTimeoutDelay = 10000
    let liveTimeout = null
    
    global.self.addEventListener('fetch', event => {
      clearTimeout(liveTimeout)
      liveTimeout = setTimeout(() => {
        console.log('User left page')
        // handle page leave
      }, liveTimeoutDelay)
      // Forward any events except for hearbeat events
      if (event.request.url.endsWith('/heartbeat')) {
        event.respondWith(
          new global.Response('Still here')
        )
      }
    })
    

提交回复
热议问题