document.addEventListener("visibilitychange", onVisibilityChange, {
    passive: true,
  });

This will fire even when someone navigates away from my page. Ofcourse this is logical. But is there a way to check if someone navigates away?

Edit: What i want is to listen if the user switches to another tab or places the window in the background, or close tab or browser. This works with visibilityChange but also fires when the user reloads the page or navigates back and forth in the history. But those are the behavior when I don't want to fire the event

1

There are 1 best solutions below

0
On

You can use setTimeout, code in setTimeout won't run on reload.

  function handleVisibilityChange (e) {
    setTimeout(() => {
        if (document.visibilityState === 'hidden') {
            console.log('HIDDEN')
        } else {
            console.log('VISIBLE')
        }
    }, 0)
}