Easiest and Reliable way to identify the last activity on a page

dom-events

Easiest%20and%20Reliable%20way%20to%20identify%20the%20last%20acti%20761668d0e209475595a4da1bbfea1178/pexels-markus-spiske-1089440.webp

visibilitychange EVENT is the easiest and reliable way to identify if you are going to see your website visitor for the last time for that page. This is an excellent article from Ilya Grigorik that talks about it.

Once the application has transitioned to background state, it may be killed without any further ceremony - e.g. the OS may terminate the process to reclaim resources, the user can swipe away the app in the task manager. As a result, you should assume that "clean shutdowns" that fire the pagehide, beforeunload, and unload events are the exception, not the rule.

// The event fires when
// 1. A user switches tab
// 2. Minimizes the browser window
// 3. Closes the tab
// 4. ......
document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') {
      navigator.sendBeacon('/this-is-probably-the-last-you-will-see-me')
  }
})
... Loading comments