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



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') {
... Loading comments